Skip to content

Instantly share code, notes, and snippets.

@silegon
Created July 11, 2016 02:45
Show Gist options
  • Save silegon/f627ffbe5a445a5ebd59860ca2563fb0 to your computer and use it in GitHub Desktop.
Save silegon/f627ffbe5a445a5ebd59860ca2563fb0 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
import base64
from Crypto.Cipher import AES
from Crypto import Random
BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
unpad = lambda s : s[:-ord(s[len(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:]))
if __name__ == "__main__":
key = "RainID39"
message = "0c2441ca-885d-488f-bf8b-cc6a423d67771468233499"
pad_key = pad(key)
aes = AESCipher(pad_key)
encrypt_message = aes.encrypt(message)
print pad_key
print message
print encrypt_message
print aes.decrypt(encrypt_message)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment