Python實(shí)現(xiàn)密鑰密碼(加解密)實(shí)例詳解
密鑰密碼
''' 如密鑰短語(yǔ)密碼為: university -> universty 明文: abcdefghijklmnopqrstuvwxyz 密文:jklmopqwxzuniverstyabcdfgh '''
構(gòu)造映射字典
# 構(gòu)造映射 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)) # 構(gòu)造映射 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('請(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)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python將txt文檔每行內(nèi)容循環(huán)插入數(shù)據(jù)庫(kù)的方法
今天小編就為大家分享一篇python將txt文檔每行內(nèi)容循環(huán)插入數(shù)據(jù)庫(kù)的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-12-12從零學(xué)python系列之從文件讀取和保存數(shù)據(jù)
在Python一般都是運(yùn)用內(nèi)置函數(shù)open()與文件進(jìn)行交互,下面說(shuō)說(shuō)具體用法2014-05-05Django數(shù)據(jù)庫(kù)(SQlite)基本入門(mén)使用教程
django有默認(rèn)自帶的數(shù)據(jù)庫(kù),當(dāng)然也可以用其他的數(shù)據(jù)庫(kù),下面這篇文章主要給大家介紹了關(guān)于Django數(shù)據(jù)庫(kù)(SQlite)基本入門(mén)使用教程的相關(guān)資料,需要的朋友可以參考下2022-07-07Python壓縮模塊zipfile實(shí)現(xiàn)原理及用法解析
這篇文章主要介紹了Python壓縮模塊zipfile實(shí)現(xiàn)原理及用法解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-08-08Python?哈希表的實(shí)現(xiàn)——字典詳解
這篇文章主要介紹了Python?哈希表的實(shí)現(xiàn)——字典,那么今天我們就來(lái)看看哈希表的原理以及如何實(shí)現(xiàn)一個(gè)簡(jiǎn)易版的?Python?哈希表,需要的朋友可以參考下2023-11-11