5前面发漏了,现在补上
原理
仿射密码也是一般单表替代密码的一个特例,是一种线性变换。
仿射密码的明文空间和密文空间与移位密码相同,但密钥空间为 K={(k1,k2)| k1,k2∈Z26,gcd(k1,26)=1}
对任意m∈M,c∈C,k = (k1,k2)∈K,
定义加密变换为:c = Ek (m) = k1 m +k2 (mod 26)
相应解密变换为: m = Dk (c) = k1-1 (c-k2) (mod 26)
编程
python实现:
# 字母表
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
# X:原文,Y:密文,a、b密钥,
# 加密函数:Y = (aX + b)%52,
# 解密函数:X = (a逆)*(Y-b)%52
# 通过拓展欧几里得定理求a对于整数环中得逆元
def exgcd(a,b,arr):
if b == 0:
arr[0] = 1
arr[1] = 0
return a
r = exgcd(b,a%b,arr)
tmp = arr[0]
arr[0] = arr[1]
arr[1] = tmp - int(a/b)*arr[1]
return r
def Get_ei(a,b):
arr = [0,1,]
r = exgcd(a,b,arr)
if r == 1:
return int ((arr[0] % b + b )%b)
else :
return -1
#加密
def encryption(k1,k2,message):
a = message
t = ''
for i in a:
if i in LETTERS:
c = LETTERS.index(i)
Y = (k1 * c + k2)%52
t += LETTERS[Y]
else:
t += i
return t
#解密
def decryption(k1,k2,message):
a = message
t = ''
K_K1 = Get_ei(k1,52)
for j in a:
if j in LETTERS:
c = LETTERS.index(j)
X = (K_K1 * (c - k2))%52
t += LETTERS[X]
else:
t += j
return t
while True:
print (u"1. encryption")
print(u"2. decryption")
choice = int(input("please input choice:"))
message = input("message:")
key1 = int(input("key1:"))
key2 = int(input("key2:"))
if choice == 1:
result = encryption(key1,key2,message)
elif choice == 2:
result = decryption(key1,key2,message)
else: print (u"Your input is wrong!")
print("result:"+result)
运行结果: