本文使用python实现一个简单的加密解密机制。
描述:结合26个字母、以一个单词作为秘钥,使用python实现简单的加密解密机制
秘钥:大写的英文字符串
明文:包含空格、大小写字母、数字等的字符串
代码实现:
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
71
72
73
74
75
76
77
78
79
|
# -*- coding: utf-8 -*-
import os,sys
reload (sys)
sys.setdefaultencoding( 'utf8' )
import string
def suanfa(key):
alp = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
jiami_key = {}
jiemi_key = {}
list0 = list (alp)
list1 = list (key)
list2 = list (alp)
for n in list1:
for m in list2:
if m = = n:
list2.remove(m)
alp1 = ''.join(list2)
key1 = key + alp1
list3 = list (key1)
a = 0
if a < len (list0):
for m in list0:
jiami_key[m] = list3[a]
a = a + 1
b = 0
if b < len (list3):
for n in list3:
jiemi_key[n] = list0[b]
b = b + 1
#print jiami_key
#print jiemi_key
return jiami_key, jiemi_key
def bianma(key_dic, data):
list_data = list (data)
data1 = []
for a in list_data:
if a = = ' ' :
data1.append(a)
elif a.islower():
a = a.upper()
if key_dic.has_key(a):
x = key_dic[a]
data1.append(x.lower())
elif a.isupper():
if key_dic.has_key(a):
x = key_dic[a]
data1.append(x)
else :
data1.append(a)
data2 = ''.join(data1)
#print data2
return data2
def main():
key = 'ZDFKJMNX'
data = 'a bdcd sFDGDSGFDG113243 3'
print "秘钥:" + key
print "明文:" + data
jiami_key, jiemi_key = suanfa(key)
miwen = bianma(jiami_key, data)
mingwen = bianma(jiemi_key, miwen)
print "加密明文所得的密文:" + miwen
print "解密密文所得的明文:" + mingwen
return True
if __name__ = = "__main__" :
main()
|
运行结果:
# python jiami.py
秘钥:ZDFKJMNX
明文:a bdcd sFDGDSGFDG113243 3
加密明文所得的密文:z dkfk qMKNKQNMKN113243 3
解密密文所得的明文:a bdcd sFDGDSGFDG113243 3
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/u013131156/article/details/78355491