Python實現密鑰密碼(加解密)實例詳解
密鑰密碼

''' 如密鑰短語密碼為: 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 密鑰密碼內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
python將txt文檔每行內容循環(huán)插入數據庫的方法
今天小編就為大家分享一篇python將txt文檔每行內容循環(huán)插入數據庫的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-12-12

