今天上密码学的课,听老师介绍了一些古典密码学的加密方法,就想着自己下来用脚本实现一个加解密。
以下是今天写的脚本,可以完成对可见字符的加解密。
加密需要一个明文和密钥。
解密需要密文和密钥

脚本如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#encoding:utf-8
'''可见字符ascii码范围为32到126'''
def encode_m():
Message = raw_input("请输入待加密的明文:")
Key = raw_input("请输入密钥:")

message_len = len(Message)
key_len = len(Key)

n = message_len/key_len
m = message_len%key_len

New_key = Key*n+Key[0:m]

Ciphertext = []
for i,j in zip(Message, New_key):
c = ord(i)+ord(j)
c = c%126
Ciphertext.append(chr(c))
print("经过加密的密文是:")
print "".join(Ciphertext).encode('utf-8')

def decode_c():
'''密文对应的计算ascii码范围不会超过252'''
Ciphertext = raw_input("请输入待解密的密文:")
Key = raw_input("请输入密钥:")

ciphertext_len = len(Ciphertext)
key_len = len(Key)

n = ciphertext_len / key_len
m = ciphertext_len % key_len

New_key = Key * n + Key[0:m]

Message = []
# (key + message)%126 = cipheretext
# message = cipheretext - key or cipheretext + 126 -key
for i, j in zip(Ciphertext, New_key):
if ord(i) > ord(j) and ((ord(i)-ord(j)) > 32):
s = chr(ord(i)-ord(j))
Message.append(s)

elif ord(i) > ord (j) and ((ord(i)-ord(j)) < 32):
s = chr(126 + ord(i) - ord(j))
Message.append(s)

elif ord(i) < ord(j):
s = chr(126 + ord(i) - ord(j))
Message.append(s)
else:
print "密钥或者密文有误!"
print "解密得到的明文是:"
print "".join(Message)
def main():
print "请选择:"
print "1.加密"
print "2.解密"
command = raw_input("你的选择:")
if command == "1":
while 1:
encode_m()
elif command == "2":
while 1:
decode_c()
elif command == "exit":
exit()

if __name__ == '__main__':
main()

下面是脚本加解密的效果图:
加密:

解密:

成功!

× 请我吃糖~
打赏二维码