Can someone provide me code to encrypt / decrypt using m2crypto aes256 CBC using Python
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.
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.
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
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()
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.
© 2022 - 2024 — McMap. All rights reserved.