python中Crypto的注意事项

今天没事用python的AES测试的时候,重复调用AES的encrypt发现每次结果都不一样,原来原因就是因为AES构建的对象只能使用一次,不允许重复使用

见如下代码:


#coding=utf-8

'''
加密
'''

from Crypto.Cipher import AES
from Crypto import Random

def testAES():
    block_size = AES.block_size
    key = 'a'*block_size
    iv = Random.new().read(block_size)

    cipher = AES.new(key, AES.MODE_CBC, iv)
    msg = iv + cipher.encrypt('f'*block_size)
    # 重复调用会出错,计算出出来的结果不正确
    # msg = iv + cipher.encrypt('f'*block_size)

    print('encrypt=%s\n' % msg)
    print('decrypt=%s\n' % cipher.decrypt(msg)[block_size:])

if __name__ == '__main__':
    testAES()

你可能感兴趣的:(python)