Skip to content

Instantly share code, notes, and snippets.

@tchn
Created May 8, 2013 13:35
Show Gist options
  • Save tchn/5540454 to your computer and use it in GitHub Desktop.
Save tchn/5540454 to your computer and use it in GitHub Desktop.
A python m2crypto usage example, simply encrypt/decrypting AES-128/ECB
#!/bin/env python
# m2crypt.py <mode> <key> <data>
import M2Crypto
import binascii
import sys
mode = sys.argv[1]
key = sys.argv[2]
data = sys.argv[3]
def get_cryptor( op, key, alg='aes_128_ecb', iv=None ):
if iv == None:
iv = '\0' * 16
cryptor = M2Crypto.EVP.Cipher( alg=alg, key=key, iv=iv, op=op)
return cryptor
def encrypt( key, plaintext ):
cryptor = get_cryptor( 1, key )
ret = cryptor.update( plaintext )
ret = ret + cryptor.final()
ret = binascii.hexlify( ret )
return ret
def decrypt( key, ciphertext ):
cryptor = get_cryptor( 0, key )
ciphertext = binascii.unhexlify( ciphertext )
ret = cryptor.update( ciphertext )
ret = ret + cryptor.final()
return ret
if mode == 'ENC':
print encrypt( key, data )
elif mode == 'DEC':
print decrypt( key, data )
else:
sys.exit(1)
@akottisa
Copy link

Hi ,

I am new to python. While decrypt i am getting below error. Can you please help

Traceback (most recent call last):
File "./crypto.py", line 61, in
print decrypt( key, data )
File "./crypto.py", line 55, in decrypt
ret = ret + cryptor.final()
File "/usr/lib64/python2.7/site-packages/M2Crypto/EVP.py", line 128, in final
return m2.cipher_final(self.ctx)
M2Crypto.EVP.EVPError: bad decrypt

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment