利用Python产生加密表和解密表的实现方法


Posted in Python onOctober 15, 2019

序言:

这是我第一次写博客,有不足之处,希望大家指出,谢谢!

这次的题目一共有三个难度,分别是简单,中等偏下,中等。对于一些刚刚入门的小伙伴来说,比较友好。废话不多说,直接进入正题。

正文:

简单难度:

【题目要求】:
实现以《三国演义》为密码本,对输入的中文文本进行加密和解密。至于加密方式,最简单的从0开始,一直往后,有多个字,就最多到多少。

【分析】:

1.知识背景:需要用到文件的读写操作,以及字典和集合的相关知识。 

 2思路:现将文件读取进来,然后对文字进行依次编码,存入字典中.

【代码】:

#------------------------------简单难度-----------------------------------
def Load_file_easy(path):
  #[注]返回值是一个set,不可进行数字索引
  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)
#写入同级目录下的文件中,如果不存在文件,则会新创建
#(博主的运行环境是:Ubuntu,win系统的小伙伴可能会在文件末尾加上.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))

中等偏下难度:

【题目要求】:

对《三国演义》的电子文档进行页的划分,以400个字为1页,每页20行20列,那么建立每个字对应的八位密码表示,其中前1~4位为页码,5、6位为行号,7、8位为这一行的第几列。例如:实:24131209,表示字“实”出现在第2413页的12行的09列。   利用此方法对中文文本进行加密和解密。

【分析】

和简单难度相比,就是加密的方式产生了不同,所以简单难度的框架可以保留。 
加密方式:首先要知道这个电子文档有多少页,可以len(Str)//400,就得到了多少页(我觉得多一页少一页没啥影响就没有+1了),然后就是要对每一个字能正确的得到它的行号和列号,具体方法见代码。

【代码】:

def Load_file_middle(path):
  with open(path,'r',encoding='utf8') as file:
    Str = file.read()
  return Str
 
def Encode(Str):
  Encode_dict = {}
  #得到页数
  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)   
    #得到行号row和列号col
    for j in range(400):
      col = str(j)
      col = col.zfill(2)
    #这里稍微说一下:比如02是第三列,12是第13列,112是第13列,看看规律就可以了
      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))

中等难度(只针对英文!)

【题目要求】:现监听到敌方加密后的密文100篇,但是不知道敌方的加密表,但是知道该密码表是由用一个英文字母代替另一个英文字母的方式实现的,现请尝试破译该密码。(注意:只针对英文)

【分析】:

知识背景:需要爬虫的相关知识
思路:找到每一个字符使用的频率,明文和密文中频率出现相近的字符就可以确定为同一个字符,剩下的就和前面的一样了
【代码】:

先把爬虫的代码贴出来:

文件名: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
  #正则表达式
  #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)
 
    #构建正则
    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):
  #删掉汉字、符号等
  result1 = re.sub('[<p> </p> u3000]','',str)
  result = ''.join(re.findall(r'[A-Za-z]', result1))
  return result

主程序:

import Crawler
 
#产生一个密文加密表
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():
  #爬取文章作为提取明文概率的计算文本
  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("爬虫发生意外!")
  
  path = 'eassy_org'
  with open(path) as file:
    org = str(file.read().splitlines())
    org = org.lower()
   #创建一个密文
  cipher_dict = Creat_cipher_dict(5)
  print(cipher_dict)
  #这里密文我已经爬取好了,存在本地了,爬取过程同上面大同小异
  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]])
  #至此 ,密文产生好了,每一个字母的概率也计算好了,可以说,工作完成了一大半了
  Decode_dict = Decode(cipher,org)
  print(Decode_dict)
if __name__ == '__main__':
  main()

最后还是将结果贴出来给大家看一下:

利用Python产生加密表和解密表的实现方法

上面一个字典是我创建出来的加密表,后一个是根据每个字符出现的概率反解出来的加密表,可见二者的相似程度具有很大的相似度。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
如何高效使用Python字典的方法详解
Aug 31 Python
python使用生成器实现可迭代对象
Mar 20 Python
Python操作mongodb数据库进行模糊查询操作示例
Jun 09 Python
Python对excel文档的操作方法详解
Dec 10 Python
对python中Json与object转化的方法详解
Dec 31 Python
python处理DICOM并计算三维模型体积
Feb 26 Python
python 实现视频 图像帧提取
Dec 10 Python
Django 批量插入数据的实现方法
Jan 12 Python
TensorFlow实现保存训练模型为pd文件并恢复
Feb 06 Python
利用Python实现斐波那契数列的方法实例
Jul 26 Python
详解Django关于StreamingHttpResponse与FileResponse文件下载的最优方法
Jan 07 Python
python opencv通过按键采集图片源码
May 20 Python
python多线程并发及测试框架案例
Oct 15 #Python
浅析PEP570新语法: 只接受位置参数
Oct 15 #Python
浅析PEP572: 海象运算符
Oct 15 #Python
Python 导入文件过程图解
Oct 15 #Python
Python3.8对可迭代解包的改进及用法详解
Oct 15 #Python
Python 3.8正式发布,来尝鲜这些新特性吧
Oct 15 #Python
Python3安装pip工具的详细步骤
Oct 14 #Python
You might like
thinkPHP5.0框架命名空间详解
2017/03/18 PHP
Ext.MessageBox工具类简介
2009/12/10 Javascript
Node.js异步I/O学习笔记
2014/11/04 Javascript
javascript实现模拟时钟的方法
2015/05/13 Javascript
javascript基于DOM实现权限选择实例分析
2015/05/14 Javascript
javascript实现给定半径求出圆的面积
2015/06/26 Javascript
javascript弹出拖动窗口
2015/08/11 Javascript
node.js抓取并分析网页内容有无特殊内容的js文件
2015/11/17 Javascript
jquery ztree异步搜索(搜叶子)实践
2016/02/25 Javascript
JS中使用变量保存arguments对象的方法
2016/06/03 Javascript
js正则表达式校验指定字符串的方法
2018/07/23 Javascript
详解webpack4之splitchunksPlugin代码包分拆
2018/12/04 Javascript
jQuery实现模拟搜索引擎的智能提示功能简单示例
2019/01/27 jQuery
JS实现的新闻列表自动滚动效果示例
2019/01/30 Javascript
javascript中可能用得到的全部的排序算法
2020/03/05 Javascript
python 切片和range()用法说明
2013/03/24 Python
PyCharm使用教程之搭建Python开发环境
2016/06/07 Python
Python3实现抓取javascript动态生成的html网页功能示例
2017/08/22 Python
python 2.7.13 安装配置方法图文教程
2018/09/18 Python
Python中请不要再用re.compile了
2019/06/30 Python
详解python解压压缩包的五种方法
2019/07/05 Python
解决Python中报错TypeError: must be str, not bytes问题
2020/04/07 Python
澳大利亚领先的优质葡萄酒拍卖会:Langton’s Fine Wines
2019/03/24 全球购物
线程的基本概念、线程的基本状态以及状态之间的关系
2012/10/26 面试题
应用电子专业学生的自我评价
2013/10/16 职场文书
高校自主招生自荐信
2013/12/09 职场文书
化妆品活动策划方案
2014/05/23 职场文书
会计专业应届生自荐信
2014/06/28 职场文书
群众路线党员自我评议范文2014
2014/09/24 职场文书
单位一把手群众路线四风问题整改措施
2014/09/25 职场文书
夫妻分居协议书范本
2014/11/28 职场文书
先进员工事迹材料
2014/12/20 职场文书
长城英文导游词
2015/01/30 职场文书
会计稽核岗位职责
2015/04/13 职场文书
Go语言切片前或中间插入项与内置copy()函数详解
2021/04/27 Golang
dubbo服务整合zipkin详解
2021/07/26 Java/Android