diff --git a/IS/Lab/Lab1/q2_autokey.py b/IS/Lab/Lab1/q2_autokey.py index 0ae235a..8771e65 100644 --- a/IS/Lab/Lab1/q2_autokey.py +++ b/IS/Lab/Lab1/q2_autokey.py @@ -25,27 +25,34 @@ def vigenere_de(ctext, vk): result.append(ch) return ''.join(result) + def autokey_en(ptext, ak): - k = ord(ak.upper()) if isinstance(ak, str) else ak - out = [] - for ch in ptext.upper(): + result = [] + ptext = ptext.upper() + current_key = ak + for ch in ptext: if ch.isalpha(): - out_ch = chr((ord(ch) - 65 + (k - 65)) % 26 + 65) - out.append(out_ch); k = ord(ch) + shift = (current_key - ord('A')) % 26 + cipher_char = chr((ord(ch) - ord('A') + shift) % 26 + ord('A')) + result.append(cipher_char) + current_key = ord(cipher_char) else: - out.append(ch) - return ''.join(out) + result.append(ch) + return ''.join(result) def autokey_de(ctext, ak): - k = ord(ak.upper()) if isinstance(ak, str) else ak - out = [] - for ch in ctext.upper(): + result = [] + ctext = ctext.upper() + current_key = ak + for ch in ctext: if ch.isalpha(): - p = chr((ord(ch) - 65 - (k - 65)) % 26 + 65) - out.append(p); k = ord(p) + shift = (current_key - ord('A')) % 26 + plain_char = chr((ord(ch) - ord('A') - shift) % 26 + ord('A')) + result.append(plain_char) + current_key = ord(plain_char) else: - out.append(ch) - return ''.join(out) + result.append(ch) + return ''.join(result) def operator(argument,ptext,ak,vk): match argument: diff --git a/IS/Lab/Lab3/DiffieHellman.py b/IS/Lab/Lab3/DiffieHellman.py index e1eb076..dcac7e0 100644 --- a/IS/Lab/Lab3/DiffieHellman.py +++ b/IS/Lab/Lab3/DiffieHellman.py @@ -38,6 +38,12 @@ def int_to_fixed_length_bytes(value: int, length_bits: int) -> bytes: def generate_keypair(p: int, g: int, private_bits: int = 256) -> tuple[int, int]: + """ + Generate a Diffie-Hellman private/public key pair. + + - private_bits controls the size of the secret exponent for performance and security. + 256 bits is a common choice for Group 14. + """ a = 0 while a < 2: a = number.getRandomNBitInteger(private_bits) @@ -46,6 +52,10 @@ def generate_keypair(p: int, g: int, private_bits: int = 256) -> tuple[int, int] def derive_shared_key(peer_public: int, private: int, p: int, key_len: int = 32) -> bytes: + """ + Compute the shared secret and derive a symmetric key using HKDF-SHA256. + Returns key_len bytes (default 32 bytes = 256-bit key). + """ shared_secret = pow(peer_public, private, p) # Use fixed-length big-endian encoding of the shared secret for KDF input shared_bytes = int_to_fixed_length_bytes(shared_secret, p.bit_length()) @@ -53,6 +63,7 @@ def derive_shared_key(peer_public: int, private: int, p: int, key_len: int = 32) return key +@dataclass class TimingResult: alice_keygen_s: float bob_keygen_s: float