Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Encrypt & Decrypt using PyCrypto AES 256
'''
Based on Stackoverflow Answer: http://stackoverflow.com/a/12525165/353550
'''
import base64
from Crypto.Cipher import AES
from Crypto import Random
BS = 16
def pad(s):
return s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
def unpad(s):
return s[:-ord(s[len(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[:16]
cipher = AES.new(self.key, AES.MODE_CBC, iv)
return unpad(cipher.decrypt(enc[16:]))
if __name__ == '__main__':
secret = 'kLF9AWRIA0H5WiLcoByZF9H3Yl7FXtBU'
aes_cipher = AESCipher(secret)
text = 'this is dummy text'
encrypted_text = aes_cipher.encrypt(text)
assert text == aes_cipher.decrypt(encrypted_text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment