M2Crypto使用AES256加密/解密

时间:2009-05-12 11:47:20

标签: python aes m2crypto

有人可以使用Python使用m2crypto aes256 CBC为我提供加密/解密的代码

5 个答案:

答案 0 :(得分:13)

M2Crypto的文档非常糟糕。有时,OpenSSL文档(m2crypto包装OpenSSL)可以提供帮助。您最好的选择是查看M2Crypto单元测试 - http://svn.osafoundation.org/m2crypto/trunk/tests/test_evp.py - 查找test_AES()方法。

答案 1 :(得分:2)

看看m2secret

  

小实用程序和模块   使用加密和解密数据   对称密钥算法。默认情况下   使用CBC的256位AES(Rijndael),   但有些选项是可配置的。   PBKDF2算法用于导出密钥   来自密码。

答案 2 :(得分:1)

def encrypt_file(key, in_filename, out_filename,iv):
    cipher=M2Crypto.EVP.Cipher('aes_256_cfb',key,iv, op=1)
    with open(in_filename, 'rb') as infile:
        with open(out_filename, 'wb') as outfile:
          outfile.write(b)
          while True:
            buf = infile.read(1024)
            if not buf:
                break
            outfile.write(cipher.update(buf))

          outfile.write( cipher.final() )  
          outfile.close()
        infile.close()

def decrypt_file(key, in_filename, out_filename,iv):
    cipher = M2Crypto.EVP.Cipher("aes_256_cfb",key , iv, op = 0)
    with open(in_filename, 'rb') as infile: 
        with open(out_filename, 'wb') as outfile:
          while True:
            buf = infile.read(1024)
            if not buf:
                break
            try:
                outfile.write(cipher.update(buf))
            except:
                print "here"
          outfile.write( cipher.final() )  
          outfile.close()
        infile.close()

答案 3 :(得分:1)

我在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

答案 4 :(得分:-1)

说到安全性,没有什么能比阅读文档更好了。

http://chandlerproject.org/bin/view/Projects/MeTooCrypto

即使我花时间去理解并制作完美的代码供你复制和粘贴,你也不知道我是否做得不错。我知道不是很有帮助,但我祝你好运并保证数据安全。