本文实例为大家分享了python实现移位加密和解密的具体代码,供大家参考,具体内容如下
代码很简单,就不多做解释啦。主要思路是将字符串转为ascii码,将大小写字母分别移位密钥表示的位数,然后转回字符串。需要注意的是,当秘钥大于26的时候,我使用循环将其不断减去26,直到密钥等效小于26为止。
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
|
def encrypt(): temp = raw_input ( "please input your sentence: " ) key = int ( raw_input ( "please input your key: " )) lista = map ( ord ,temp) lens = len (lista) for i in range (lens): a = lista[i] if 65 < = a < = 90 : a + = key while a > 90 : a - = 26 elif 97 < = a < = 122 : a + = key while a > 122 : a - = 26 lista[i] = a lista = map ( chr ,lista) lista = ''.join(lista) print lista def unencrypt(): temp = raw_input ( "please input your sentence: " ) key = int ( raw_input ( "please input your key: " )) lista = map ( ord , temp) lens = len (lista) for i in range (lens): a = lista[i] if 65 < = a < = 90 : a - = key while a < 65 : a + = 26 elif 97 < = a < = 122 : a - = key while a < 97 : a + = 26 lista[i] = a lista = map ( chr , lista) lista = ''.join(lista) print lista a = int ( raw_input ( "input 0 to encrypt and 1 to unencrypt" )) if a = = 0 : encrypt() elif a = = 1 : unencrypt() |
效果
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/St_laurence/article/details/83352951