Skip to content

Instantly share code, notes, and snippets.

@saiprasad1996
Forked from mguezuraga/AESCipher.py
Created July 21, 2017 12:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saiprasad1996/6e2f0c9340c47a8ed0da30a0c4113418 to your computer and use it in GitHub Desktop.
Save saiprasad1996/6e2f0c9340c47a8ed0da30a0c4113418 to your computer and use it in GitHub Desktop.
Encrypt & Decrypt using PyCrypto AES 256From http://stackoverflow.com/a/12525165/119849
#!/usr/bin/env python
import base64
from Crypto import Random
from Crypto.Cipher import AES
BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
unpad = lambda s : s[0:-s[-1]]
class AESCipher:
def __init__( self, key ):
self.key = hashlib.sha256(key.encode('utf-8')).digest()
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:] ))
cipher = AESCipher('mysecretpassword')
encrypted = cipher.encrypt('Secret Message A')
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