使用M2Crypto进行AES256加密/解密
有人能给我提供一些代码,用Python实现用m2crypto库进行AES256 CBC加密和解密吗?
5 个回答
3
我使用了一个围绕M2Crypto的封装,这个封装是从cryptography.io借来的:
import os
import base64
import M2Crypto
class SymmetricEncryption(object):
@staticmethod
def generate_key():
return base64.b64encode(os.urandom(48))
def __init__(self, key):
key = base64.b64decode(key)
self.iv = key[:16]
self.key = key[16:]
def encrypt(self, plaintext):
ENCRYPT = 1
cipher = M2Crypto.EVP.Cipher(alg='aes_256_cbc', key=self.key, iv=self.iv, op=ENCRYPT)
ciphertext = cipher.update(plaintext) + cipher.final()
return base64.b64encode(ciphertext)
def decrypt(self, cyphertext):
DECRYPT = 0
cipher = M2Crypto.EVP.Cipher(alg='aes_256_cbc', key=self.key, iv=self.iv, op=DECRYPT)
plaintext = cipher.update(base64.b64decode(cyphertext)) + cipher.final()
return plaintext
3
看看这个 m2secret:
这是一个小工具和模块,用来加密和解密数据,使用的是对称密钥算法。默认情况下,它使用的是256位的AES(Rijndael)加密方式,采用CBC模式,但有些选项是可以配置的。它还使用PBKDF2算法从密码中生成密钥。
14
M2Crypto的文档真的是糟糕透了。有时候,OpenSSL的文档(因为M2Crypto是基于OpenSSL的)可能会对你有帮助。最好的办法是看看M2Crypto的单元测试——你可以在这个链接找到:https://gitlab.com/m2crypto/m2crypto/blob/master/tests/test_evp.py——找找里面的test_AES()
方法。