Python實(shí)現(xiàn)密鑰密碼(加解密)實(shí)例詳解
密鑰密碼
’’’如密鑰短語(yǔ)密碼為: university -> universty明文: abcdefghijklmnopqrstuvwxyz密文:jklmopqwxzuniverstyabcdfgh’’’
構(gòu)造映射字典
# 構(gòu)造映射 asc ---> cryptdef 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))# 構(gòu)造映射 crypt ---> ascdef 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(’請(qǐng)輸入密鑰字符:’) if not x.isalpha(): print(’請(qǐng)輸入正確的密鑰格式!’) exit(0) s = input(’請(qǐng)輸入明文:’) 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(’請(qǐng)輸入密鑰字符:’) if not x.isalpha(): print(’請(qǐng)輸入正確的密鑰格式!’) exit(0) s = input(’請(qǐng)輸入密文:’) 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’請(qǐng)輸入所需的操作:編碼/E or 解碼/D: ’)try: if answer.upper() == ’E’: encode() elif answer.upper() == ’D’: decode() else: print(’輸入錯(cuò)誤!’)except KeyError: print(’請(qǐng)正確輸入小寫(xiě)字母!’)
實(shí)現(xiàn)效果
注:可以輸入空格輸出大小寫(xiě):請(qǐng)自行修改
請(qǐng)輸入所需的操作:編碼/E or 解碼/D: e請(qǐng)輸入密鑰字符:university請(qǐng)輸入明文:abcdefghijklmnopqrstuvwxyz加密后字符:jklmopqwxzuniverstyabcdfgh
請(qǐng)輸入所需的操作:編碼/E or 解碼/D: d請(qǐng)輸入密鑰字符:university請(qǐng)輸入密文:jklmopqwxzuniverstyabcdfgh解密后字符:abcdefghijklmnopqrstuvwxyz
到此這篇關(guān)于Python實(shí)現(xiàn)密鑰密碼(加解密)的文章就介紹到這了,更多相關(guān)python 密鑰密碼內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. ASP.NET MVC把數(shù)據(jù)庫(kù)中枚舉項(xiàng)的數(shù)字轉(zhuǎn)換成文字2. 用xslt+css讓RSS顯示的跟網(wǎng)頁(yè)一樣漂亮3. 《CSS3實(shí)戰(zhàn)》筆記--漸變?cè)O(shè)計(jì)(一)4. .NET擴(kuò)展方法使用實(shí)例詳解5. 測(cè)試模式 - XSL教程 - 56. 讓chatgpt將html中的圖片轉(zhuǎn)為base64方法示例7. html5手機(jī)觸屏touch事件介紹8. CSS3實(shí)現(xiàn)動(dòng)態(tài)翻牌效果 仿百度貼吧3D翻牌一次動(dòng)畫(huà)特效9. ASP.NET Core自定義中間件的方式詳解10. ASP.NET泛型三之使用協(xié)變和逆變實(shí)現(xiàn)類型轉(zhuǎn)換
