defmod_inverse(a, m): for i inrange(1, m): if (a * i) % m == 1: return i returnNone
defaffine_encrypt(text, key): result = "" a, b = key for char in text: if char.isalpha(): if char.isupper(): result += chr((a * (ord(char) - 65) + b) % 26 + 65) else: result += chr((a * (ord(char) - 97) + b) % 26 + 97) else: result += char return result
defaffine_decrypt(ciphertext, key): result = "" a, b = key a_inv = mod_inverse(a, 26) if a_inv isNone: raise ValueError("密钥错误!!!") for char in ciphertext: if char.isalpha(): if char.isupper(): result += chr((a_inv * (ord(char) - 65 - b)) % 26 + 65) else: result += chr((a_inv * (ord(char) - 97 - b)) % 26 + 97) else: result += char return result
defmod_inverse(a, m): for i inrange(1, m): if (a * i) % m == 1: return i returnNone
defaffine_decrypt(ciphertext, key): result = "" a, b = key a_inv = mod_inverse(a, 26) if a_inv isNone: raise ValueError("The key is not valid for decryption.") for char in ciphertext: if char.isalpha(): if char.isupper(): result += chr((a_inv * (ord(char) - 65 - b)) % 26 + 65) else: result += chr((a_inv * (ord(char) - 97 - b)) % 26 + 97) else: result += char return result
defbrute_force_affine(ciphertext): for a inrange(1, 26): if gcd(a, 26) == 1: for b inrange(26): possible_key = (a, b) decrypted_text = affine_decrypt(ciphertext, possible_key) print(f"Attempted Key: {possible_key}, Decrypted Text: {decrypted_text}")