代换密码算法的原理是使用替代法进行加密,就是将明文中的字符用其它字符替代后形成密文。例如,明文字母a、b、c、d,用D、E、F、G做对应替换后形成密文。
代换密码包括多种类型,如单表代换密码、多表代换密码等。下面介绍一种典型的单表代换密码——仿射密码。
'''
args = {
name:仿射变换加解密
author:Lsy
date:2020-11-18
}
'''
# 加密函数
def encrypt(Plaintext, a, b):
'''
args = {
Plaintext:需要加密的明文
a:仿射变换的第一个秘钥
b:仿射变换的第二个秘钥
ciphertext:返回加密后的密文
}
'''
ciphertext = ""
i = 0
while (i < len(Plaintext)):
m = ord(Plaintext[i])
if (m >= 65) and (m <= 90):
x = chr(((m - 65) * a + b) % 26 + 65)
elif (m >= 97) and (m <= 122):
x = chr(((m - 97) * a + b) % 26 + 97)
else:
ciphertext = '输入明文出现错误'
break
ciphertext += x
i += 1
return ciphertext
# 求逆元函数
def Inverse(a):
'''
args = {
a:需要求逆元的秘钥
y2:返回该秘钥的逆元
}
'''
x1 = 1
x2 = 0
x3 = 26
y1 = 0
y2 = 1
y3 = a
while 1:
q = x3 // y3
temp1 = y1
temp2 = y2
temp3 = y3
y1 = x1 - q * temp1
y2 = x2 - q * temp2
y3 = x3 - q * temp3
x1 = temp1
x2 = temp2
x3 = temp3
if y3 == 1:
break
return y2
# 解密函数
def decrypt(ciphertext, a, b):
'''
args = {
ciphertext:需要解密的密文
a:仿射变换的第一个秘钥
b:仿射变换的第二个秘钥
Plaintext:返回的明文
}
'''
n = Inverse(a) # 求第一个秘钥的逆元
Plaintext = ""
i = 0
while i < len(ciphertext):
c = ord(ciphertext[i])
if (c >= 65) and (c <= 90):
x = chr(n * (c - 65 - b) % 26 + 65)
elif (c >= 97) and (c <= 122):
x = chr(n * (c - 97 - b) % 26 + 97)
else:
Plaintext = "输入密文出现错误"
break
Plaintext += x
i += 1
return Plaintext
# 判断两个数是不是互为素数
def judge(a, b=26):
if a < b:
temp = a
a = b
b = temp
while 1:
temp1 = a % b
a = b
b = temp1
if b == 0:
return 0
elif b == 1:
return 1
else:
continue
# 主函数
if __name__ == "__main__":
# 加密
Plaintext = input("请输入需要加密的明文字符串:")
while 1:
a = int(input("请输入秘钥a(需要与26互素且[0,25]):"))
if judge(a) and (a >= 0) and (a <= 25):
break
else:
print("输入错误,请重试!")
while 1:
b = int(input("请输入秘钥b[0,25]:"))
if b >= 0 and b <= 25:
break
else:
print("输入错误,请重试!")
ciphertext = encrypt(Plaintext, a, b)
print("加密后的密文为:" + ciphertext)
# 解密
ciphertext = input("请输入需要解密的明文字符串:")
while 1:
a = int(input("请输入秘钥a(需要与26互素且[0,25]):"))
if judge(a) and (a >= 0) and (a <= 25):
break
else:
print("输入错误,请重试!")
while 1:
b = int(input("请输入秘钥b[0,25]:"))
if b >= 0 and b <= 25:
break
else:
print("输入错误,请重试!")
Plaintext = decrypt(ciphertext, a, b)
print("解密后的明文为:" + Plaintext)
# 请输入需要加密的明文字符串:security
# 请输入秘钥a(需要与26互素且[0,25]):7
# 请输入秘钥b[0,25]:21
# 加密后的密文为:rxjfkzyh
# 请输入需要解密的明文字符串:rxjfkzyh
# 请输入秘钥a(需要与26互素且[0,25]):7
# 请输入秘钥b[0,25]:21
# 解密后的明文为:security