Python AES 加密 pycrypto
安装
有多种方式:
- Windows 下 exe 文件,下载地址,如果有报错,可以下载 VCForPython27
pip install pycrypto
,可能会报错 microsoft visual c++ 14.0 is required,查看 https://wiki.python.org/moin/WindowsCompilers ,需要下载 Visual Studio,最后采用了第三种方法。pip install pycryptodome
,GitHub :https://github.com/Legrandin/pycryptodome
使用
python 2.7
# -*- 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 版本。
- 注释 1,如果不修改会报错
TypeError: Object type <class 'str'> cannot be passed to C code
,感谢 https://stackoverflow.com/questions/46052752/using-aes-encrypt-get-raise-typeerroronly-byte-strings-can-be-passed-to-c-code - 注释 2,报错同注释 1,key 的类型需要是 bytes。
- 注释 3,4,如果不修改会报错
TypeError: must be str, not bytes
,类型转换下即可。
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 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" 转载请保留原文链接及作者。