-
-
Save handol/4f43143dd9e7a2a8013fda841e83e672 to your computer and use it in GitHub Desktop.
AES encryption example using M2Crypto module
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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