Commit fe864afd authored by Almouhannad Hafez's avatar Almouhannad Hafez

Implement get_round_key, generate_random_key

parent 901593cf
import random
class SDES:
def __init__(self, rounds_count: int = 2, key_length: int = 9):
......@@ -8,11 +10,66 @@ class SDES:
rounds_count (int): Number of iterations to perform
key_length (int): Length of keys that will be used for encryption/decryption
"""
# SDES is a block-cipher algorithm, uses blocks of size 12 bits
self.block_size = 12
# SDED uses a fixed-length key (8bits- key) for each iteration
self.round_key_length = 8
# Type checking
if not isinstance(rounds_count, int):
raise TypeError(f"Expected 'rounds_count' to be int, got {type(rounds_count).__name__}")
raise TypeError(f"'rounds_count' must be int, got {type(rounds_count).__name__}")
if not isinstance(key_length, int):
raise TypeError(f"Expected 'key_length' to be int, got {type(key_length).__name__}")
raise TypeError(f"'key_length' must be int, got {type(key_length).__name__}")
# Validation rules
if key_length < self.round_key_length:
raise ValueError(f"'key_length' must be at least {self.round_key_length}, got {key_length}")
self.rounds_count = rounds_count
self.key_length = key_length
def get_round_key(self, key: str, round_number: int) -> str:
"""
Generate key to be used in the round
Parameters:
key (str): A binary string of length self.key_length
round_number (int): The round number
Returns:
round_key (str): The key for spcified round
"""
# Type checking
if not isinstance(key, str):
raise TypeError(f"'key' must be str, got {type(key).__name__}")
if not isinstance(round_number, int):
raise TypeError(f"'round_number' must be int, got {type(round_number).__name__}")
# Validation rules
if len(key) != self.key_length:
raise ValueError(f"'key' must be at of length {self.key_length}, got {len(key)}")
if not all(c in '01' for c in key):
raise ValueError(f"'key' must only contain '0' and '1'")
if round_number < 0:
raise ValueError(f"'round_number' must be >= 0, got {round_number}")
round_key = ''
# Get 8 bits from key starting from round_number and applying round-robin
for i in range(8):
index = (round_number + i) % self.key_length
round_key += key[index]
return round_key
def generate_random_key(self) -> str:
"""
Generate a random binary key of length = self.key_length
Returns:
key (str): A string representing the random binary key
"""
# Generate a random binary string by selecting '0' or '1' for each position
key = ''.join(random.choice('01') for _ in range(self.key_length))
return key
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment