密钥密码
'''
如密钥短语密码为: university -> universty
明文: abcdefghijklmnopqrstuvwxyz
密文:jklmopqwxzuniverstyabcdfgh
'''
构造映射字典
# 构造映射 asc ---> crypt
def dic(x):
list_x =[]
list_z = []
for i in x:
list_x.append(ord(i))
for i in range(97,123):
if i not in list_x:
list_x.append(i)
list_ = list_x[26-len(x)-1:]
cr = list_+list_x[:26-len(list_)]
for i in range(97,123):
list_z.append(i)
return dict(map(lambda x,y:[x,y],list_z,cr))
# 构造映射 crypt ---> asc
def dic_2(x):
list_x =[]
list_z = []
for i in x:
list_x.append(ord(i))
for i in range(97,123):
if i not in list_x:
list_x.append(i)
list_ = list_x[26-len(x)-1:]
cr = list_+list_x[:26-len(list_)]
for i in range(97,123):
list_z.append(i)
return dict(map(lambda x,y:[x,y],cr,list_z))
密钥去重
# 密钥去重
def remove(x):
unique_x = []
for i in x:
if i not in unique_x:
unique_x.append(i)
return unique_x
加解密
# 加密
def encode():
x = input('请输入密钥字符:')
if not x.isalpha():
print('请输入正确的密钥格式!')
exit(0)
s = input('请输入明文:')
print('加密后字符:',end='')
unique_x = remove(x)
dic_ = dic(unique_x)
for i in s:
if i.isspace():
print(' ', end='')
else:
print(chr(dic_[ord(i)]),end='')
# 解密
def decode():
x = input('请输入密钥字符:')
if not x.isalpha():
print('请输入正确的密钥格式!')
exit(0)
s = input('请输入密文:')
print('解密后字符:',end='')
unique_x = remove(x)
dic_ = dic_2(unique_x)
for i in s:
if i.isspace():
print(' ',end='')
else:
print(chr(dic_[ord(i)]),end='')
程序入口
# 输入指令
answer = input(f'请输入所需的操作:编码/E or 解码/D: ')
try:
if answer.upper() == 'E':
encode()
elif answer.upper() == 'D':
decode()
else:
print('输入错误!')
except KeyError:
print('请正确输入小写字母!')
实现效果
注:可以输入空格
输出大小写:请自行修改
请输入所需的操作:编码/E or 解码/D: e
请输入密钥字符:university
请输入明文:abcdefghijklmnopqrstuvwxyz
加密后字符:jklmopqwxzuniverstyabcdfgh请输入所需的操作:编码/E or 解码/D: d
请输入密钥字符:university
请输入密文:jklmopqwxzuniverstyabcdfgh
解密后字符:abcdefghijklmnopqrstuvwxyz
到此这篇关于Python实现密钥密码(加解密)的文章就介绍到这了,更多相关python 密钥密码内容请搜索python博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持python博客!
Powered By python教程网 鲁ICP备18013710号
python博客 - 小白学python最友好的网站!