利用Python產(chǎn)生加密表和解密表的實(shí)現(xiàn)方法
序言:
這是我第一次寫博客,有不足之處,希望大家指出,謝謝!
這次的題目一共有三個(gè)難度,分別是簡(jiǎn)單,中等偏下,中等。對(duì)于一些剛剛?cè)腴T的小伙伴來(lái)說(shuō),比較友好。廢話不多說(shuō),直接進(jìn)入正題。
正文:
簡(jiǎn)單難度:
【題目要求】:
實(shí)現(xiàn)以《三國(guó)演義》為密碼本,對(duì)輸入的中文文本進(jìn)行加密和解密。至于加密方式,最簡(jiǎn)單的從0開始,一直往后,有多個(gè)字,就最多到多少。
【分析】:
1.知識(shí)背景:需要用到文件的讀寫操作,以及字典和集合的相關(guān)知識(shí)。
2思路:現(xiàn)將文件讀取進(jìn)來(lái),然后對(duì)文字進(jìn)行依次編碼,存入字典中.
【代碼】:
#------------------------------簡(jiǎn)單難度-----------------------------------
def Load_file_easy(path):
#[注]返回值是一個(gè)set,不可進(jìn)行數(shù)字索引
file = open(path,'r',encoding='utf8')
Str = file.read()
Str = set(Str)
file.close()
return Str
def Encode_easy(Lstr):
Sstr = list(set(Lstr))
Encode_Dict = {}
for i in range(len(Lstr)):
Encode_Dict[Sstr[i]] = i
return Encode_Dict
def Decode_easy(Encode_dict):
List1 = Encode_dict.keys()
List2 = Encode_dict.values()
Decode_Dict = dict(list(zip(List2,List1)))
return Decode_Dict
path = 'SanGuo.txt'
Str = list(Load_file_easy(path))
Encode_dict = Encode_easy(Str)
Decode_dict = Decode_easy(Encode_dict)
#寫入同級(jí)目錄下的文件中,如果不存在文件,則會(huì)新創(chuàng)建
#(博主的運(yùn)行環(huán)境是:Ubuntu,win系統(tǒng)的小伙伴可能會(huì)在文件末尾加上.txt 啥的,略略略)
with open('easy_degree_Encode_dict','w') as file:
file.write(str(Encode_dict))
with open('easy_degree_Decode_dict','w') as file:
file.write(str(Decode_dict))
中等偏下難度:
【題目要求】:
對(duì)《三國(guó)演義》的電子文檔進(jìn)行頁(yè)的劃分,以400個(gè)字為1頁(yè),每頁(yè)20行20列,那么建立每個(gè)字對(duì)應(yīng)的八位密碼表示,其中前1~4位為頁(yè)碼,5、6位為行號(hào),7、8位為這一行的第幾列。例如:實(shí):24131209,表示字“實(shí)”出現(xiàn)在第2413頁(yè)的12行的09列。 利用此方法對(duì)中文文本進(jìn)行加密和解密。
【分析】
和簡(jiǎn)單難度相比,就是加密的方式產(chǎn)生了不同,所以簡(jiǎn)單難度的框架可以保留。
加密方式:首先要知道這個(gè)電子文檔有多少頁(yè),可以len(Str)//400,就得到了多少頁(yè)(我覺得多一頁(yè)少一頁(yè)沒啥影響就沒有+1了),然后就是要對(duì)每一個(gè)字能正確的得到它的行號(hào)和列號(hào),具體方法見代碼。
【代碼】:
def Load_file_middle(path):
with open(path,'r',encoding='utf8') as file:
Str = file.read()
return Str
def Encode(Str):
Encode_dict = {}
#得到頁(yè)數(shù)
for i in range(len(Str)//400):
page = i + 1
temp = Str[(i*400):(400*(i+1))]
page_str = str(page)
page_str = page_str.zfill(4)
#得到行號(hào)row和列號(hào)col
for j in range(400):
col = str(j)
col = col.zfill(2)
#這里稍微說(shuō)一下:比如02是第三列,12是第13列,112是第13列,看看規(guī)律就可以了
if int(col[-2])%2 ==0:
col = int(col[-1]) + 1
else:
col = int(col[-1]) + 11
row = str(j//20 +1)
row = row.zfill(2)
col = (str(col)).zfill(2)
#print(page_str,row,col)
Encode_dict[temp[j]] = page_str+row+str(col)
return Encode_dict
def Decode(Encode_dict): List1 = Encode_dict.keys() List2 = Encode_dict.values() Decode_Dict = dict(list(zip(List2,List1))) return Decode_Dict
path = 'SanGuo.txt'
Str = list(Load_file_middle(path))
Encode_dict = Encode(Str)
Decode_dict = Decode(Encode_dict)
with open('middle_low_degree_Encode_dict','w') as file:
file.write(str(Encode_dict))
with open('middle_low_degree_Decode_dict','w') as file:
file.write(str(Decode_dict))
中等難度(只針對(duì)英文!)
【題目要求】:現(xiàn)監(jiān)聽到敵方加密后的密文100篇,但是不知道敵方的加密表,但是知道該密碼表是由用一個(gè)英文字母代替另一個(gè)英文字母的方式實(shí)現(xiàn)的,現(xiàn)請(qǐng)嘗試破譯該密碼。(注意:只針對(duì)英文)
【分析】:
知識(shí)背景:需要爬蟲的相關(guān)知識(shí)
思路:找到每一個(gè)字符使用的頻率,明文和密文中頻率出現(xiàn)相近的字符就可以確定為同一個(gè)字符,剩下的就和前面的一樣了
【代碼】:
先把爬蟲的代碼貼出來(lái):
文件名:Crawler.py
import re
import requests
def Crawler(url):
#url2 = 'https://www.diyifanwen.com/yanjianggao/yingyuyanjianggao/'
response = requests.get(url).content.decode('gbk','ignore')
html = response
#正則表達(dá)式
#example_for_2 = re.compile(r'<li><a.*?target="_blank".*?href="(.*?)title=(.*?)>.*?</a></li>')
example_for_1 = re.compile(r'<i class="iTit">\s*<a href="(.*?)" rel="external nofollow" target="_blank">.*?</a>')
resultHref =re.findall(example_for_1,html)
resultHref = list(resultHref)
Fil = []
for each_url in resultHref:
each_url = 'https:' + str(each_url)
#構(gòu)建正則
exam = re.compile(r'<div class="mainText">\s*(.*?)\s*<!--精彩推薦-->')
response2 = requests.get(each_url).content.decode('gbk','ignore')
html2 = response2
result_eassy = re.findall(exam,html2)
Fil.append(result_eassy)
return str(Fil)
def WriteIntoFile(Fil,path):
#寫入文件
with open(path,'a') as file:
for i in range(len(Fil)//200):
file.write(Fil[200*i:200*(i+1)])
file.write('\r\n')
if file is not None:
print("success")
def Deleter_Chiness(str):
#刪掉漢字、符號(hào)等
result1 = re.sub('[<p> </p> u3000]','',str)
result = ''.join(re.findall(r'[A-Za-z]', result1))
return result
主程序:
import Crawler
#產(chǎn)生一個(gè)密文加密表
def Creat_cipher_dict(num=5):
cipher_dict = {}
chri = [chr(i) for i in range(97,123)]
for i in range(26-num):
cipher_dict[chri[i]] = chr(ord(chri[i])+num)
for i in range(num):
cipher_dict[chri[26-num+i]] = chr(ord(chri[i]))
return cipher_dict
def Get_Frequency(Str):
Frequency = [0] * 26
cnt = 0
chri = [chr(i) for i in range(97, 123)]
Frequency_dict = {}
for i in range(len(Str)):
Ascii = ord(Str[i]) - 97
# 排除一些還存在的異常字符
if Ascii >= 0 and Ascii <= 25:
Frequency[Ascii] += 1
cnt += 1
Frequency_dict[chr(Ascii+97)] = Frequency[Ascii]
for key in Frequency_dict.keys():
#Frequency[i] = Frequency[i] / cnt
Frequency_dict[key] = Frequency_dict[key]/cnt
Frequency_dict = sorted(Frequency_dict.items(),key = lambda x:x[1],reverse=True)
return dict(Frequency_dict)
def Decode(cipher,org):
Frequency_for_cipher = Get_Frequency(cipher)
Frequency_for_org = Get_Frequency(org)
#print(Frequency_for_org)
#print(Frequency_for_cipher)
Decode_dict = {}
Frequency = list(Frequency_for_org.keys())
i = 0
for key in list(Frequency_for_cipher.keys()):
Decode_dict[key] = Frequency[i]
i +=1
return Decode_dict
def main():
#爬取文章作為提取明文概率的計(jì)算文本
for i in range(1,15):
url = 'https://edu.pcbaby.com.cn/resource/yjg/yy/'+'index_'+str(i)+'.html'
try:
Fil = Crawler.Crawler(url)
eassy = Crawler.Deleter_Chiness(Fil)
path = 'eassy_org'
Crawler.WriteIntoFile(path,eassy)
except :
print("爬蟲發(fā)生意外!")
path = 'eassy_org'
with open(path) as file:
org = str(file.read().splitlines())
org = org.lower()
#創(chuàng)建一個(gè)密文
cipher_dict = Creat_cipher_dict(5)
print(cipher_dict)
#這里密文我已經(jīng)爬取好了,存在本地了,爬取過(guò)程同上面大同小異
with open('eassy_cipher','r') as file:
Fil2 = str(file.read().splitlines())
Fil2 = Fil2.lower()
cipher = []
for i in range(len(Fil2)):
if ord(Fil2[i])>=97 and ord(Fil2[i])<=123:
cipher.append(cipher_dict[Fil2[i]])
#至此 ,密文產(chǎn)生好了,每一個(gè)字母的概率也計(jì)算好了,可以說(shuō),工作完成了一大半了
Decode_dict = Decode(cipher,org)
print(Decode_dict)
if __name__ == '__main__':
main()
最后還是將結(jié)果貼出來(lái)給大家看一下:

上面一個(gè)字典是我創(chuàng)建出來(lái)的加密表,后一個(gè)是根據(jù)每個(gè)字符出現(xiàn)的概率反解出來(lái)的加密表,可見二者的相似程度具有很大的相似度。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- python模塊hashlib(加密服務(wù))知識(shí)點(diǎn)講解
- python中的RSA加密與解密實(shí)例解析
- python RC4加密操作示例【測(cè)試可用】
- python rsa實(shí)現(xiàn)數(shù)據(jù)加密和解密、簽名加密和驗(yàn)簽功能
- Flask框架實(shí)現(xiàn)的前端RSA加密與后端Python解密功能詳解
- python文字和unicode/ascll相互轉(zhuǎn)換函數(shù)及簡(jiǎn)單加密解密實(shí)現(xiàn)代碼
- Python實(shí)現(xiàn)最常見加密方式詳解
- 如何基于python實(shí)現(xiàn)腳本加密
相關(guān)文章
python常用request庫(kù)與lxml庫(kù)操作方法整理總結(jié)
一路學(xué)習(xí),一路總結(jié),技術(shù)就是這樣,應(yīng)用之后,在進(jìn)行整理,才可以加深印象。本篇文字為小節(jié)篇,核心總結(jié) requests 庫(kù)與 lxml 庫(kù)常用的操作2021-08-08
python 將列表里的字典元素合并為一個(gè)字典實(shí)例
這篇文章主要介紹了python 將列表里的字典元素合并為一個(gè)字典實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-09-09
python return實(shí)現(xiàn)匯率轉(zhuǎn)換器教程示例
這篇文章主要為大家介紹了python return實(shí)現(xiàn)匯率轉(zhuǎn)換器教程示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06
使用Python實(shí)現(xiàn)合并多個(gè)Excel文件
合并Excel可以將多個(gè)文件中的數(shù)據(jù)合并到一個(gè)文件中,這樣可以幫助我們更好地匯總和管理數(shù)據(jù),本文主要介紹了如何使用第三方Python庫(kù) Spire.XLS for Python 實(shí)現(xiàn)以上兩種合并Excel文件的需求,有需要的可以了解下2023-12-12
Python通過(guò)psd-tools解析PSD文件的實(shí)現(xiàn)
本文主要介紹了Python通過(guò)psd-tools解析PSD文件的實(shí)現(xiàn),主要包括如何獲取PSD文件的基本信息、遍歷圖層、提取圖層詳細(xì)信息、保存和創(chuàng)建PSD文件,感興趣的可以了解一下2023-12-12
pytorch模型部署 pth轉(zhuǎn)onnx的方法
這篇文章主要介紹了pytorch模型部署 pth轉(zhuǎn)onnx的相關(guān)知識(shí),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-05-05
python的scikit-learn將特征轉(zhuǎn)成one-hot特征的方法
今天小編就為大家分享一篇python的scikit-learn將特征轉(zhuǎn)成one-hot特征的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-07-07
Python自定義函數(shù)計(jì)算給定日期是該年第幾天的方法示例
這篇文章主要介紹了Python自定義函數(shù)計(jì)算給定日期是該年第幾天的方法,結(jié)合具體實(shí)例形式分析了Python日期時(shí)間計(jì)算相關(guān)操作技巧,需要的朋友可以參考下2019-05-05

