Python AES 加密 pycrypto‎

  1. 安装
  2. 使用
    1. python 2.7
    2. python 3.6

安装

有多种方式:

  1. Windows 下 exe 文件,下载地址,如果有报错,可以下载 VCForPython27
  2. pip install pycrypto,可能会报错 microsoft visual c++ 14.0 is required,查看 https://wiki.python.org/moin/WindowsCompilers ,需要下载 Visual Studio,最后采用了第三种方法。
  3. pip install pycrypto‎dome,GitHub :https://github.com/Legrandin/pycryptodome

使用

python 2.7

参考 https://stackoverflow.com/questions/12524994/encrypt-decrypt-using-pycrypto-aes-256/12525165#12525165

# -*- coding: utf-8 -*
import time
from binascii import b2a_hex, a2b_hex
from Crypto.Cipher import AES

BS = AES.block_size
# 加密算法
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
# 解密算法
unpad = lambda s: s[:-ord(s[len(s) - 1:])]

class AESCipher:
    def __init__(self, key):
        self.key = key
        self.iv = b'0102030405060708'

    # 加密
    def encrypt(self, raw):
        raw = pad(raw)
        cipher = AES.new(self.key, AES.MODE_CBC, self.iv)
        return b2a_hex(cipher.encrypt(raw))

    # 解密
    def decrypt(self, enc):
        cipher = AES.new(self.key, AES.MODE_CBC, self.iv)
        return unpad(cipher.decrypt(a2b_hex(enc)))

timeStamp = str(int(time.time()))
key = b'AD0001' + timeStamp
aa = AESCipher(key)
s = aa.encrypt('123456')
print("加密:" + s)
ss = aa.decrypt(s)
print("解密:" + ss)

python 3.6

# -*- coding: utf-8 -*
import time
from binascii import b2a_hex, a2b_hex
from Crypto.Cipher import AES

BS = AES.block_size
# 加密算法
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
# 解密算法
unpad = lambda s: s[:-ord(s[len(s) - 1:])]

class AESCipher:
    def __init__(self, key):
        self.key = key
        self.iv = b'0102030405060708'

    # 加密
    def encrypt(self, raw):
        raw = pad(raw).encode("utf-8") # 1
        cipher = AES.new(self.key, AES.MODE_CBC, self.iv)
        return b2a_hex(cipher.encrypt(raw))

    # 解密
    def decrypt(self, enc):
        cipher = AES.new(self.key, AES.MODE_CBC, self.iv)
        return unpad(cipher.decrypt(a2b_hex(enc)))

timeStamp = str(int(time.time()))
key = bytes("AD0001"+timeStamp,'utf-8') # 2
aa = AESCipher(key)
s = aa.encrypt('123456')
print("加密:" + str(s, encoding="utf-8")) # 3
ss = aa.decrypt(s)
print("解密:" + str(ss, encoding="utf-8")) # 4

由 python 2.7 版本修改至 python 3.6 版本。



转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 bin07280@qq.com

文章标题:Python AES 加密 pycrypto‎

文章字数:512

本文作者:Bin

发布时间:2018-05-18, 13:17:55

最后更新:2019-08-06, 00:07:35

原始链接:http://coolview.github.io/2018/05/18/Python/Python%20AES%20%E5%8A%A0%E5%AF%86%20pycrypto%E2%80%8E/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

目录