Fork me on GitHub

维吉尼亚密码的加密解密

维吉尼亚密码的加密解密

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
# -*- coding:utf-8 -*-

def weijiniya_jiemi(ciphertext,key):
ascii='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
keylen=len(key)
ctlen=len(ciphertext)
plaintext = ''
i = 0
while i < ctlen:
j = i % keylen
k = ascii.index(key[j])
m = ascii.index(ciphertext[i])
if m < k:
m += 26
plaintext += ascii[m-k]
i += 1
print plaintext

def weijiniya_jiami(plaintext,key):
ascii='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
keylen=len(key)
ptlen=len(plaintext)
ciphertext = ''
i = 0
while i < ptlen:
j = i % keylen
k = ascii.index(key[j])
m = ascii.index(plaintext[i])
ciphertext += ascii[(m+k)%26]
i += 1
print ciphertext

def main():
print 'CHOICE:'
print '1:weijiniya_jiami'
print '2:weijiniya_jiemi'
choice = input()
if choice == 1:
plaintext = input('jiama_string1:')
key = input('key:')
weijiniya_jiami(plaintext,key)
elif choice == 2:
ciphertext = input('jiemi_string1:')
key = input('key:')
weijiniya_jiemi(ciphertext,key)
else:
print('error!')
main()

if __name__ == '__main__':
main()

好像cmd窗口有点问题,中文一直显示不出来,就直接用拼音了哈哈哈。。。

再加一个凯撒的,虽然直接有网址可以解:

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
# -*- coding:utf-8 -*-
def change(c,i):
c = c.lower()
num =ord(c)
ifnum >=97andnum <=122:
num =97+ ((num -97) + i) %26
returnchr(num)

def kaisa_jiami(string,i):
string_new =''
forsinstring:
string_new += change(s,i)
print(string_new)
return string_new

def kaisa_jiemi(string):
for i in range(25):
print('\n', i,'\n')
i +=1
kaisa_jiami(string,i)

def main():
print('请选择需要的操作:')
print('1:凯撒加密')
print('2:凯撒解密')
choice =input()
if choice ==1:
string =input('请输入需要加密的字符串:')
num =int(input('请输入需要偏移的位数:'))
kaisa_jiami(string,num)
else if choice ==2:
string =input('请输入需要解密的字符串:')
kaisa_jiemi(string)

else:
print('输入错误,请重试!')
main()
if__name__ =='__main__':
main()
-------------本文结束感谢您的阅读-------------