Skip to content

Instantly share code, notes, and snippets.

@twkang
Created April 5, 2014 09:14
Show Gist options
  • Save twkang/9989456 to your computer and use it in GitHub Desktop.
Save twkang/9989456 to your computer and use it in GitHub Desktop.
AES encryption example using M2Crypto module
import sys
import base64
from M2Crypto import Rand, EVP
ENC_METHOD="aes_256_cbc"
MODE_B64, MODE_BIN = 0, 1
IV_LEN = 16
def encrypt(s, key, mode=MODE_BIN):
iv = Rand.rand_bytes(IV_LEN) # can be : iv = os.urandom(IV_LEN)
cipher = EVP.Cipher(ENC_METHOD, key=key, iv=iv, op=1)
v = cipher.update(s)
v = iv + v + cipher.final()
if mode == MODE_B64:
v = base64.urlsafe_b64encode(v)
return v
def decrypt(s, key, mode=MODE_BIN):
if mode == MODE_B64:
s = base64.urlsafe_b64decode(s)
iv = s[:IV_LEN]
cipher = EVP.Cipher(ENC_METHOD, key=key, iv=iv, op=0)
v = cipher.update(s[IV_LEN:])
v = v + cipher.final()
return v
if __name__ == "__main__":
passwd = 'mypassword'
s = encrypt('test data for m2crypto encryption & decryption', passwd, mode=MODE_B64)
print len(s), repr(s)
s = decrypt(s, passwd, mode=MODE_B64)
print len(s), repr(s)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment