Skip to content

Instantly share code, notes, and snippets.

@twkang
Created April 5, 2014 09:14
Show Gist options
  • Select an option

  • Save twkang/9989456 to your computer and use it in GitHub Desktop.

Select an option

Save twkang/9989456 to your computer and use it in GitHub Desktop.

Revisions

  1. twkang created this gist Apr 5, 2014.
    32 changes: 32 additions & 0 deletions m2crypto_aes.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,32 @@
    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)