Python3对称加密算法AES、DES3实例详解


Posted in Python onDecember 06, 2018

本文实例讲述了Python3对称加密算法AES、DES3。分享给大家供大家参考,具体如下:

python3.6此库安装方式,需要pip3 install pycryptodome。

如有site-packages中存在crypto、pycrypto,在pip之前,需要pip3 uninstall cryptopip3 uninstall pycrypto,否则无法安装成功。

C:\WINDOWS\system32>pip3 install pycryptodome
Collecting pycryptodome
  Downloading https://files.pythonhosted.org/packages/0f/5d/a429a53eacae3e13143248c3868c76985bcd0d75858bd4c25b574e51bd4d/pycryptodome-3.6.3-cp36-cp36m-win_amd64.whl (7.9MB)
    100% |????????????????????????????????| 7.9MB 111kB/s
Installing collected packages: pycryptodome
Successfully installed pycryptodome-3.6.3

这里顺带说一下pycrypto,这个库已经有很久没有人维护了,如果需要安装此库,需要先安装 VC++ build tools

然后将 ~\BuildTools\VC\Tools\MSVC\14.15.26726\include 目录下的 stdint.h 拷贝到 C:\Program Files (x86)\Windows Kits\10\Include\10.0.17134.0\ucrt 下。(Win10 需管理员权限)

接着将同目录下的 inttypes.h 中的 #include <stdint.h> (第十四行),改成 #include "stdint.h"

然后使用 pip3 install pycrypto,就能直接安装了。

注:如果不是业务需要,请尽可能使用 pycryptodome。

AES:

import Crypto.Cipher.AES
import Crypto.Random
import base64
import binascii
def auto_fill(x):
  if len(x) <= 32:
    while len(x) not in [16, 24, 32]:
      x += " "
    return x.encode()
  else:
    raise "密钥长度不能大于32位!"
key = "asd"
content = "abcdefg1234567"
x = Crypto.Cipher.AES.new(auto_fill(key), Crypto.Cipher.AES.MODE_ECB)
a = base64.encodebytes(x.encrypt(auto_fill(content)))
b = x.decrypt(base64.decodebytes(a))
print(a)
print(b)
a = binascii.b2a_base64(x.encrypt(auto_fill(content)))
b = x.decrypt(binascii.a2b_base64(a))
print(a)
print(b)
key = "dsa"
iv = Crypto.Random.new().read(16)  # 向量,必须为16字节
content = "1234567abcdefg"
y = Crypto.Cipher.AES.new(auto_fill(key), Crypto.Cipher.AES.MODE_CBC, iv)
c = binascii.b2a_base64(y.encrypt(auto_fill(content)))
z = Crypto.Cipher.AES.new(auto_fill(key), Crypto.Cipher.AES.MODE_CBC, iv)
d = z.decrypt(binascii.a2b_base64(c))
print(c)
print(d)

运行结果:

b'jr/EIUp32kLHc3ypZZ1cyg==\n'
b'abcdefg1234567  '
b'jr/EIUp32kLHc3ypZZ1cyg==\n'
b'abcdefg1234567  '
b'j+Ul9KQd0HnuiHW3z9tD7A==\n'
b'1234567abcdefg  '

DES3:

import Crypto.Cipher.DES3
import base64
import binascii
def auto_fill(x):
  if len(x) > 24:
    raise "密钥长度不能大于等于24位!"
  else:
    while len(x) < 16:
      x += " "
    return x.encode()
key = "asd"
content = "abcdefg1234567"
x = Crypto.Cipher.DES3.new(auto_fill(key), Crypto.Cipher.DES3.MODE_ECB)
a = base64.encodebytes(x.encrypt(auto_fill(content)))
print(a)
b = x.decrypt(base64.decodebytes(a))
print(b)
a = binascii.b2a_base64(x.encrypt(auto_fill(content)))
b = x.decrypt(binascii.a2b_base64(a))
print(a)
print(b)

运行结果:

b'/ee3NFKeNqEk/qMNd1mjog==\n'
b'abcdefg1234567  '
b'/ee3NFKeNqEk/qMNd1mjog==\n'
b'abcdefg1234567  '

附:AES的工厂模式封装Cipher_AES.py(封装Crypto.Cipher.AES)

'''
Created on 2018年7月7日
@author: ray
'''
import Crypto.Cipher.AES
import Crypto.Random
import base64
import binascii
class Cipher_AES:
  pad_default = lambda x, y: x + (y - len(x) % y) * " ".encode("utf-8")
  unpad_default = lambda x: x.rstrip()
  pad_user_defined = lambda x, y, z: x + (y - len(x) % y) * z.encode("utf-8")
  unpad_user_defined = lambda x, z: x.rstrip(z)
  pad_pkcs5 = lambda x, y: x + (y - len(x) % y) * chr(y - len(x) % y).encode("utf-8")
  unpad_pkcs5 = lambda x: x[:-ord(x[-1])]
  def __init__(self, key="abcdefgh12345678", iv=Crypto.Random.new().read(Crypto.Cipher.AES.block_size)):
    self.__key = key
    self.__iv = iv
  def set_key(self, key):
    self.__key = key
  def get_key(self):
    return self.__key
  def set_iv(self, iv):
    self.__iv = iv
  def get_iv(self):
    return self.__iv
  def Cipher_MODE_ECB(self):
    self.__x = Crypto.Cipher.AES.new(self.__key.encode("utf-8"), Crypto.Cipher.AES.MODE_ECB)
  def Cipher_MODE_CBC(self):
    self.__x = Crypto.Cipher.AES.new(self.__key.encode("utf-8"), Crypto.Cipher.AES.MODE_CBC, self.__iv.encode("utf-8"))
  def encrypt(self, text, cipher_method, pad_method="", code_method=""):
    if cipher_method.upper() == "MODE_ECB":
      self.Cipher_MODE_ECB()
    elif cipher_method.upper() == "MODE_CBC":
      self.Cipher_MODE_CBC()
    cipher_text = b"".join([self.__x.encrypt(i) for i in self.text_verify(text.encode("utf-8"), pad_method)])
    if code_method.lower() == "base64":
      return base64.encodebytes(cipher_text).decode("utf-8").rstrip()
    elif code_method.lower() == "hex":
      return binascii.b2a_hex(cipher_text).decode("utf-8").rstrip()
    else:
      return cipher_text.decode("utf-8").rstrip()
  def decrypt(self, cipher_text, cipher_method, pad_method="", code_method=""):
    if cipher_method.upper() == "MODE_ECB":
      self.Cipher_MODE_ECB()
    elif cipher_method.upper() == "MODE_CBC":
      self.Cipher_MODE_CBC()
    if code_method.lower() == "base64":
      cipher_text = base64.decodebytes(cipher_text.encode("utf-8"))
    elif code_method.lower() == "hex":
      cipher_text = binascii.a2b_hex(cipher_text.encode("utf-8"))
    else:
      cipher_text = cipher_text.encode("utf-8")
    return self.unpad_method(self.__x.decrypt(cipher_text).decode("utf-8"), pad_method)
  def text_verify(self, text, method):
    while len(text) > len(self.__key):
      text_slice = text[:len(self.__key)]
      text = text[len(self.__key):]
      yield text_slice
    else:
      if len(text) == len(self.__key):
        yield text
      else:
        yield self.pad_method(text, method)
  def pad_method(self, text, method):
    if method == "":
      return Cipher_AES.pad_default(text, len(self.__key))
    elif method == "PKCS5Padding":
      return Cipher_AES.pad_pkcs5(text, len(self.__key))
    else:
      return Cipher_AES.pad_user_defined(text, len(self.__key), method)
  def unpad_method(self, text, method):
    if method == "":
      return Cipher_AES.unpad_default(text)
    elif method == "PKCS5Padding":
      return Cipher_AES.unpad_pkcs5(text)
    else:
      return Cipher_AES.unpad_user_defined(text, method)

使用方法:

        加密:Cipher_AES(key [, iv]).encrypt(text, cipher_method [, pad_method [, code_method]])

        解密:Cipher_AES(key [, iv]).decrypt(cipher_text, cipher_method [, pad_method [, code_method]])

key:密钥(长度必须为16、24、32)

iv:向量(长度与密钥一致,ECB模式不需要)

text:明文(需要加密的内容)

cipher_text:密文(需要解密的内容)

cipher_method:加密方法,目前只有"MODE_ECB"、"MODE_CBC"两种

pad_method:填充方式,解决 Java 问题选用"PKCS5Padding"

code_method:编码方式,目前只有"base64"、"hex"两种

来段调用封装类 Cipher_AES 的 demo_Cipher_AES.py,方便大家理解:

import Cipher_AES
key = "qwedsazxc123321a"
iv = key[::-1]
text = "我爱小姐姐,可小姐姐不爱我 - -"
cipher_method = "MODE_CBC"
pad_method = "PKCS5Padding"
code_method = "base64"
cipher_text = Cipher_AES(key, iv).encrypt(text, cipher_method, pad_method, code_method)
print(cipher_text)
text = Cipher_AES(key, iv).decrypt(cipher_text, cipher_method, pad_method, code_method)
print(text)
'''
运行结果:
uxhf+MoSko4xa+jGOyzJvYH9n5NvrCwEHbwm/A977CmGqzg+fYE0GeL5/M5v9O1o
我爱小姐姐,可小姐姐不爱我 - -
'''
Python 相关文章推荐
tornado框架blog模块分析与使用
Nov 21 Python
Python中使用select模块实现非阻塞的IO
Feb 03 Python
Python实现并行抓取整站40万条房价数据(可更换抓取城市)
Dec 14 Python
使用Python对SQLite数据库操作
Apr 06 Python
Flask框架Jinjia模板常用语法总结
Jul 19 Python
Python 列表去重去除空字符的例子
Jul 20 Python
Python3并发写文件与Python对比
Nov 20 Python
对Tensorflow中tensorboard日志的生成与显示详解
Feb 04 Python
Python实现AI自动抠图实例解析
Mar 05 Python
Keras 利用sklearn的ROC-AUC建立评价函数详解
Jun 15 Python
Python中使用aiohttp模拟服务器出现错误问题及解决方法
Oct 31 Python
python 安全地删除列表元素的方法
Mar 16 Python
Python http接口自动化测试框架实现方法示例
Dec 06 #Python
python的常用模块之collections模块详解
Dec 06 #Python
Django管理员账号和密码忘记的完美解决方法
Dec 06 #Python
Python操作json的方法实例分析
Dec 06 #Python
Python多线程应用于自动化测试操作示例
Dec 06 #Python
Python实现多属性排序的方法
Dec 05 #Python
python通过ffmgep从视频中抽帧的方法
Dec 05 #Python
You might like
PHP 5昨天隆重推出--PHP 5/Zend Engine 2.0新特性
2006/10/09 PHP
自动分页的不完整解决方案
2007/01/12 PHP
php setcookie(name, value, expires, path, domain, secure) 参数详解
2013/06/28 PHP
PHP连接SQLServer2005方法及代码
2013/12/26 PHP
php二维数组转成字符串示例
2014/02/17 PHP
PHP实现在线阅读PDF文件的方法
2015/06/23 PHP
PHP实现的二分查找算法实例分析
2017/12/19 PHP
php微信分享到朋友圈、QQ、朋友、微博
2019/02/18 PHP
PHP压缩图片功能的介绍
2019/03/21 PHP
PHP实现随机发放扑克牌
2020/04/21 PHP
javascript 复杂的嵌套环境中输出单引号和双引号
2009/05/26 Javascript
兼容IE、FireFox、Chrome等浏览器的xml处理函数js代码
2011/11/30 Javascript
JS动态创建Table,Tr,Td并赋值的具体实现
2013/07/05 Javascript
JavaScript你不知道的一些数组方法
2017/08/18 Javascript
浅谈Vue.js 组件中的v-on绑定自定义事件理解
2017/11/17 Javascript
小程序组件之仿微信通讯录的实现代码
2018/09/12 Javascript
vue+layui实现select动态加载后台数据的例子
2019/09/20 Javascript
[04:49]期待西雅图之战 2016国际邀请赛中国区预选赛WINGS战队赛后采访
2016/06/29 DOTA
[02:32]“虐狗”镜头慎点 2016国际邀请赛中国区预选赛现场玩家采访
2016/06/28 DOTA
python轻松查到删除自己的微信好友
2016/01/10 Python
Python简单实现安全开关文件的两种方式
2016/09/19 Python
安装python3的时候就是输入python3死活没有反应的解决方法
2018/01/24 Python
Python测试人员需要掌握的知识
2018/02/08 Python
终端命令查看TensorFlow版本号及路径的方法
2018/06/13 Python
Linux上使用Python统计每天的键盘输入次数
2019/04/17 Python
python global关键字的用法详解
2019/09/05 Python
浅谈pytorch卷积核大小的设置对全连接神经元的影响
2020/01/10 Python
教你使用Sublime text3搭建Python开发环境及常用插件安装另分享Sublime text3最新激活注册码
2020/11/12 Python
英国潮流网站:END.(全球免邮)
2017/01/16 全球购物
瑞典时尚服装购物网站:Miinto.se
2017/10/30 全球购物
菲律宾领先的在线时尚商店:Zalora菲律宾
2018/02/08 全球购物
Wiggle美国:英国骑行、跑步、游泳、铁人三项商店
2018/10/27 全球购物
自荐信的格式
2014/03/10 职场文书
交通安全月活动总结
2015/05/08 职场文书
资金申请报告范文
2015/05/14 职场文书
2016教师给学生的毕业寄语
2015/12/04 职场文书