生成0-25的随机置换,实现单表代换的加解密
import random
#单表代换加密
def encode(plaintext,key):
print(plaintext,key)
for p in plaintext:
temp=key[ ord(p.upper())-ord("A")]
print(chr(ord("A")+temp),end="")
#单表代换解密
def decode(cipher,key):
print(cipher,key)
for c in cipher:
cnum= ord(c.upper())-ord("A")
for i in range(0,26):
if(key[i]==cnum):
break
print((chr(i+ord("A"))),end="")
#key=random.sample(range(0,26),26)
key= [3, 15, 24, 20, 23, 25, 1, 4, 21, 2, 5, 17, 22, 14, 11, 6, 8, 10, 18, 19, 9, 0, 7, 13, 12, 16]
encode("abcdef",key)
print()
decode("DPYUXZ",key)
测试输出
abcdef [3, 15, 24, 20, 23, 25, 1, 4, 21, 2, 5, 17, 22, 14, 11, 6, 8, 10, 18, 19, 9, 0, 7, 13, 12, 16]
DPYUXZ
DPYUXZ [3, 15, 24, 20, 23, 25, 1, 4, 21, 2, 5, 17, 22, 14, 11, 6, 8, 10, 18, 19, 9, 0, 7, 13, 12, 16]
ABCDEF
随机生成密钥key(a,b),其中gcd(a,26)=1,实现仿射密码的加解密
#key=(a,b)
import random
#欧几里得判断两数最大公因数是不是1
def gcd(a,b):
if(a<b):
return gcd(b,a)
while(a%b!=0):
temp=b
b=a%b
a=temp
return b
#遍历求逆
def qiuNi(a):
for i in range(1,26):
if((a*i-1)%26==0):
return i
#仿射加密
def encode(plaintext,a,b):
print(plaintext,a,b)
for p in plaintext:
if(p==" "):
print(" ",end="")
pnum=ord(p.upper())-ord("A")
temp=(pnum*a+b)%26
print(chr(temp+ord("A")),end="")
#仿射解密
def decode(cipher,a,b):
print(cipher,a,b)
a_Ni=qiuNi(a)
for c in cipher:
if(c==" "):
print(" ",end="")
cnum=ord(c.upper())-ord("A")
temp=(cnum-b)*a_Ni%26
print(chr(temp+ord("A")),end="")
a=random.randint(1,25)
b=random.randint(1,25)
#plaintext=input()
while gcd(a,26)!=1:
a=random.randint(1,25)
#encode(plaintext,a,b)
encode("hot",9,3)
print()
decode("ozs",9,3)
测试输出
hot 9 3
OZS
ozs 9 3
HOT