MIT-Curricular/IS/Lab/Lab1/q6_affine_bf.py
2025-08-05 09:25:24 +05:30

42 lines
1.1 KiB
Python

def main():
# Affine cipher: E(x) = (ax + b) mod 26
# Given: "ab" -> "GL"
# a=0, b=1 -> G=6, L=11
ciphertext = "XPALASXYFGFUKPXUSOGEUTKCDGEXANMGNVS"
for a in range(1, 26):
if gcd(a, 26) != 1:
continue
for b in range(26):
# if key produces "ab" -> "GL"
if (a * 0 + b) % 26 == 6 and (a * 1 + b) % 26 == 11:
a_inv = mod_inverse(a, 26)
decrypted = ""
for char in ciphertext:
if char.isalpha():
y = ord(char.upper()) - ord('A')
x = (a_inv * (y - b)) % 26
decrypted += chr(x + ord('A'))
else:
decrypted += char
print(f"Key found: a={a}, b={b}")
print(f"Ciphertext: {ciphertext}")
print(f"Decrypted: {decrypted}")
return
def gcd(a, b):
while b:
a, b = b, a % b
return a
def mod_inverse(a, m):
for i in range(1, m):
if (a * i) % m == 1:
return i
return None
if __name__ == '__main__':
main()