Skip to content

Instantly share code, notes, and snippets.

@shahinism
Forked from swinton/AESCipher.py
Last active October 17, 2017 14:05
Show Gist options
  • Save shahinism/0089add0db3eb0d81d31689a6126cb00 to your computer and use it in GitHub Desktop.
Save shahinism/0089add0db3eb0d81d31689a6126cb00 to your computer and use it in GitHub Desktop.
Encrypt & Decrypt using PyCrypto AES 256From http://stackoverflow.com/a/12525165/119849
import base64
from Crypto import Random
from Crypto.Cipher import AES
class AESCipher:
def __init__(self, key):
"""Key length should be of size 16, 24 or 32 based on AES function description
(eg. len(key) == 32 will provide AES256)
"""
self.key = key
@staticmethod
def _pad_(s):
BS = 32
return s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
@staticmethod
def _unpad_(s):
s = s.decode()
return s[0:-ord(s[-1])]
def encrypt(self, raw):
raw = self._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)).decode()
def decrypt(self, enc):
enc = base64.b64decode(enc)
iv = enc[:16]
cipher = AES.new(self.key, AES.MODE_CBC, iv)
return self._unpad_(cipher.decrypt(enc[16:]))
# cipher = AESCipher('8d22a853a9dd4a47b9db6e62c961c3c8')
# encrypted = cipher.encrypt('Store the tue user information obtained in the id_token in flask session.')
# decrypted = cipher.decrypt(encrypted)
# print(encrypted)
# print(decrypted)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment