pycrypto:AES加密详解

  最近在写接口自动化脚本,需要的payload参数需要加密,而采用的加密标准为AES,因此特地去学了一下,发现专门有加密算法库支持这种加密算法,就是PyCrypto

PyCrypto是一个免费的加密算法库,支持常见的DES、AES、以及MD5、SHA等各种HASH运算

PyPi地址:https://pypi.org/project/pycrypto/

这篇博文只对AES加密进行重点讲解

#coding:utf-8
from Crypto.Cipher import AES

#加密
cryptor = AES.new('This is a key123', AES.MODE_CBC, 'This is an iv456')
msg='the answer is no'
ciphertext = cryptor.encrypt(msg)
print(ciphertext)

#解密
cryptor2 = AES.new('This is a key123', AES.MODE_CBC, 'This is an iv456')
plain_text=cryptor2.decrypt(ciphertext)
print(plain_text)

1)加密

'This is an iv456'为key,长度有着严格的要求,必须是16/24或者32位,否则将抛出错误:ValueError: AES key must be either 16, 24, or 32 bytes long
'This is an iv456'为VI,长度要求更加严格,只能为16位,否则将抛出错误:ValueError: IV must be 16 bytes long
通过encrypt()对msg字符串进行加密得到ciphertext

2)解密
要想对加密字符串进行解密,必须知道加密时使用的key和VI,通过decrypt()方法对加密字符串进行解密
如果key和VI错误,则将无法得到正确的解密字符串,解密失败后将会得到一个新的加密字符串

3)关于安装PyCrypto模块遇到问题的请参考本人的另外一篇博客:https://www.cnblogs.com/Elaine1/p/10180260.html

 

猜你喜欢

转载自www.cnblogs.com/Elaine1/p/10184363.html