Skip to content

Instantly share code, notes, and snippets.

@pjama
Created April 18, 2013 17:44
Show Gist options
  • Save pjama/5414727 to your computer and use it in GitHub Desktop.
Save pjama/5414727 to your computer and use it in GitHub Desktop.
AES encryption / decryption module. Based on SO response, http://stackoverflow.com/a/12525165
#!/usr/bin/python
from Crypto import Random
from Crypto.Cipher import AES
import base64
BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
unpad = lambda s : s[0:-ord(s[-1])]
class AESCipher:
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[:16]
cipher = AES.new(self.key, AES.MODE_CBC, iv)
return unpad(cipher.decrypt(enc[16:]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment