能否提供一个用Python实现的仿射密码(Affine Cipher)加密和解密算法的例子代码?
时间: 2024-12-22 11:31:20 浏览: 15
当然可以。在Python中,我们可以使用模运算和简单的算术操作来实现仿射密码。这是一个基础的示例:
```python
def affine_cipher_encrypt(text, a, b):
encrypted_text = []
for char in text:
if char.isalpha(): # 只对字母字符加密
shift = (ord(char.lower()) - ord('a') + a) % 26
encrypted_char = chr(((shift + b - 1) % 26) + ord('a'))
else:
encrypted_char = char
encrypted_text.append(encrypted_char)
return ''.join(encrypted_text)
def affine_cipher_decrypt(encrypted_text, a, b):
a_inverse = inverse(a, 26)
decrypted_text = []
for char in encrypted_text:
if char.isalpha():
shift = ((ord(char.lower()) - ord('a') - b) * a_inverse) % 26
decrypted_char = chr((shift + ord('a')) % 26)
else:
decrypted_char = char
decrypted_text.append(decrypted_char)
return ''.join(decrypted_text)
# 计算a的逆元函数(模26)
def inverse(x, mod):
x %= mod
y = mod
u = 1
v = 0
while y != 0:
q = x // y
t = x
x = y
y = t % y
t = u
u = v
v = t - q * v
if x < 0:
x += mod
return u
# 示例使用
message = "Hello, World!"
key_a = 5
key_b = 7
encrypted_message = affine_cipher_encrypt(message, key_a, key_b)
print(f"Encrypted message: {encrypted_message}")
decrypted_message = affine_cipher_decrypt(encrypted_message, key_a, key_b)
print(f"Decrypted message: {decrypted_message}")
```
在这个例子中,`affine_cipher_encrypt`用于加密文本,而`affine_cipher_decrypt`用于解密。`inverse`函数用于计算给定值a在模26下的逆数,这是仿射加密的关键步骤。
阅读全文