Modified Lab 1 IS
This commit is contained in:
parent
fdc634b589
commit
933a52b3a8
8 changed files with 166 additions and 384 deletions
|
@ -0,0 +1,47 @@
|
|||
def main():
|
||||
# Affine cipher: E(x) = (ax + b) mod 26
|
||||
# Given: "ab" -> "GL"
|
||||
# a=0, b=1 -> G=6, L=11
|
||||
# So: 6 = (a*0 + b) mod 26 -> b = 6
|
||||
# And: 11 = (a*1 + b) mod 26 -> 11 = (a + 6) mod 26 -> a = 5
|
||||
|
||||
ciphertext = "XPALASXYFGFUKPXUSOGEUTKCDGEXANMGNVS"
|
||||
|
||||
# Try all possible values of a and b for affine cipher
|
||||
for a in range(1, 26):
|
||||
# a must be coprime to 26
|
||||
if gcd(a, 26) != 1:
|
||||
continue
|
||||
|
||||
for b in range(26):
|
||||
# Check if this key produces "ab" -> "GL"
|
||||
if (a * 0 + b) % 26 == 6 and (a * 1 + b) % 26 == 11:
|
||||
# Found the key, now decrypt the message
|
||||
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()
|
Loading…
Add table
Add a link
Reference in a new issue