Skip to content

Instantly share code, notes, and snippets.

@daGrevis
Created August 21, 2013 13:14
Show Gist options
  • Select an option

  • Save daGrevis/6294300 to your computer and use it in GitHub Desktop.

Select an option

Save daGrevis/6294300 to your computer and use it in GitHub Desktop.
Little abstraction for PyCrypto
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
@daGrevis

Copy link
Copy Markdown
Author

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