Created
August 21, 2013 13:14
-
-
Save daGrevis/6294300 to your computer and use it in GitHub Desktop.
Little abstraction for PyCrypto
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 base64 | |
| from Crypto import Random | |
| from Crypto.Cipher import AES | |
| BLOCK_SIZE = 16 | |
| pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * chr(BLOCK_SIZE - len(s) % BLOCK_SIZE) | |
| unpad = lambda s: s[0:-ord(s[-1])] | |
| class AESCipher(object): | |
| def __init__(self, key): | |
| self.key = key | |
| def encrypt(self, raw): | |
| raw = pad(raw) | |
| iv = Random.new().read(AES.block_size) | |
| cipher = AES.new(self.key, AES.MODE_CBC, iv) | |
| return base64.b64encode(iv + cipher.encrypt(raw)) | |
| def decrypt(self, enc): | |
| enc = base64.b64decode(enc) | |
| iv = enc[:BLOCK_SIZE] | |
| cipher = AES.new(self.key, AES.MODE_CBC, iv) | |
| return unpad(cipher.decrypt(enc[BLOCK_SIZE:])) | |
| cipher = AESCipher(key="x" * 32) | |
| text = "Hello, world!" | |
| print(text) | |
| encrypted = cipher.encrypt(text) | |
| print(encrypted) | |
| decrypted = cipher.decrypt(encrypted) | |
| print(decrypted) | |
| assert text == decrypted |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Warning!