Skip to content

Instantly share code, notes, and snippets.

@wowkin2
Created May 7, 2018 14:59
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 wowkin2/143fc63deb775fbc5fc9e251ec761736 to your computer and use it in GitHub Desktop.
Save wowkin2/143fc63deb775fbc5fc9e251ec761736 to your computer and use it in GitHub Desktop.
AES encoding sample
import base64
from Crypto.Cipher import AES
class AESCipher(object):
BS = 16
def __init__(self, key):
self.key = key
self.pad = lambda s: s + (self.BS - len(s) % self.BS) * chr(self.BS - len(s) % self.BS).encode()
self.unpad = lambda s: s[:-ord(s[len(s)-1:])]
@staticmethod
def iv():
"""
The initialization vector to use for encryption or decryption.
It is ignored for MODE_ECB and MODE_CTR.
"""
return chr(0) * 16
def encrypt(self, message):
"""
It is assumed that you use Python 3.0+, so plaintext's type must be str type(== unicode).
"""
message = message.encode()
raw = self.pad(message)
cipher = AES.new(self.key, AES.MODE_CBC, self.iv())
enc = cipher.encrypt(raw)
return base64.b64encode(enc).decode('utf-8')
def decrypt(self, enc):
enc = base64.b64decode(enc)
cipher = AES.new(self.key, AES.MODE_CBC, self.iv())
dec = cipher.decrypt(enc)
return self.unpad(dec).decode('utf-8')
def main():
data = "Hello world!"
key = '1234567890ABCDEF' # 16 chars long
code = AESCipher(key).encrypt(data)
print(code)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment