Reputation:
Can someone provide me code to encrypt / decrypt using m2crypto aes256 CBC using Python
Upvotes: 7
Views: 11328
Reputation: 41747
M2Crypto's documentation is terrible. Sometimes the OpenSSL documentation (m2crypto wraps OpenSSL) can help. Your best bet is to look at the M2Crypto unit tests -- https://gitlab.com/m2crypto/m2crypto/blob/master/tests/test_evp.py -- look for the test_AES()
method.
Upvotes: 14
Reputation: 4901
I use following wrapper around M2Crypto (borrowed from 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
Upvotes: 3
Reputation: 2087
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()
Upvotes: 2
Reputation: 6160
Take a look at m2secret:
Small utility and module for encrypting and decrypting data using symmetric-key algorithms. By default uses 256-bit AES (Rijndael) using CBC, but some options are configurable. PBKDF2 algorithm used to derive key from password.
Upvotes: 3
Reputation: 327
When it comes to security nothing beats reading the documentation.
http://chandlerproject.org/bin/view/Projects/MeTooCrypto
Even if I took the time to understand and make the perfect code for you to copy and paste, you would have no idea if I did a good job or not. Not very helpful I know, but I wish you luck and secure data.
Upvotes: -1