python3 Crypto模块实例解析
作者:互联网
一 模块简介
1.简介
python的Crypto模块是安全hash函数(例如SHA256 和RIPEMD160)以及各种主流的加解密算法的((AES, DES, RSA, ElGamal等)的集合。
二 实例解析
1.AES实例
from os import urandom from Crypto.Cipher import AES # For Generating cipher text secret_key = urandom(16) iv = urandom(16) obj = AES.new(secret_key, AES.MODE_CBC, iv) # Encrypt the message message = b'Xu sheng test me' print('Original message is: ', message) encrypted_text = obj.encrypt(message) print('The encrypted text', encrypted_text)
输出结果:
Original message is: b'Xu sheng test me' The encrypted text b'\x80\xaf\x93\xef\xd6\xab\xe4t\xad\xdf\xfbgChSt'
2. AES解密
from os import urandom from Crypto.Cipher import AES # For Generating cipher text secret_key = urandom(16) iv = urandom(16) obj = AES.new(secret_key, AES.MODE_CBC, iv) # Encrypt the message message = b'Lorem Ipsum text' print('Original message is: ', message) encrypted_text = obj.encrypt(message) print('The encrypted text', encrypted_text) # Decrypt the message rev_obj = AES.new(secret_key, AES.MODE_CBC, iv) decrypted_text = rev_obj.decrypt(encrypted_text) print('The decrypted text', decrypted_text.decode('utf-8'))输出结果:
Original message is: b'Lorem Ipsum text' The encrypted text b'\xe9\xfcC\xb3\x132&n\xc7\xdeZe9\xeb\xab\xf3' The decrypted text Lorem Ipsum text三 注意事项 1.错误: TypeError: Object type <class 'str'> cannot be passed to C code 解决方案: AES_KEY、IV还有要加密的数据转换成bytes类型就可以了。
标签:AES,obj,text,urandom,Crypto,实例,encrypted,message,python3 来源: https://www.cnblogs.com/dylancao/p/16282771.html