仿射密码python
时间: 2023-07-26 11:05:58 浏览: 100
Python实现仿射密码
5星 · 资源好评率100%
以下是一个简单的 Python 代码实现仿射密码:
```python
def egcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
def modinv(a, m):
g, x, y = egcd(a, m)
if g != 1:
raise Exception('No modular inverse')
else:
return x % m
def affine_encrypt(text, key):
# 将文本转换为大写并去除空格
text = text.upper().replace(" ", "")
# 确保a和m互质
a = key[0]
m = 26
if egcd(a, m)[0] != 1:
raise ValueError('a and m must be coprime.')
# 加密文本
cipher = ""
for char in text:
if char.isalpha():
# 将字符转换为数字并进行加密
cipher += chr(((a * (ord(char) - 65)) % m) + 65)
else:
cipher += char
return cipher
def affine_decrypt(cipher, key):
# 确保a和m互质
a = key[0]
m = 26
if egcd(a, m)[0] != 1:
raise ValueError('a and m must be coprime.')
# 计算a的模逆
a_inv = modinv(a, m)
# 解密密文
text = ""
for char in cipher:
if char.isalpha():
# 将字符转换为数字并进行解密
text += chr(((a_inv * (ord(char) - 65)) % m) + 65)
else:
text += char
return text
# 例子
text = "Hello, World!"
key = (5, 8) # a=5, b=8
cipher = affine_encrypt(text, key)
print("Encrypted text:", cipher)
decrypted_text = affine_decrypt(cipher, key)
print("Decrypted text:", decrypted_text)
```
这个代码实现了仿射密码的加密和解密功能。输入一个文本和一个密钥(由a和b组成),输出加密后的文本或解密后的文本。
阅读全文