Skip to content

Instantly share code, notes, and snippets.

@Sen-Zhang
Created October 11, 2018 00:49
Show Gist options
  • Save Sen-Zhang/50a8109fc944424e9ead6102d56c8a6e to your computer and use it in GitHub Desktop.
Save Sen-Zhang/50a8109fc944424e9ead6102d56c8a6e to your computer and use it in GitHub Desktop.
AES Cipher in Python
import base64
import hashlib
from Crypto.Cipher import AES
from django.conf import settings
AES_BLOCK_SIZE = 16
AES_KEY = settings.SECRET_KEY[:32]
AES_MODE = AES.MODE_CBC
def encrypt(plain_text: str) -> str:
padded_plain_text = _pad(plain_text)
iv = _get_iv(padded_plain_text)
cipher = AES.new(AES_KEY, AES_MODE, iv)
return base64.b64encode(iv + cipher.encrypt(padded_plain_text)).decode()
def decrypt(cipher_text: str) -> str:
decoded_text = base64.b64decode(cipher_text.encode())
cipher = AES.new(AES_KEY, AES_MODE, decoded_text[:AES_BLOCK_SIZE])
return _unpad(cipher.decrypt(decoded_text[AES_BLOCK_SIZE:])).decode()
def _get_iv(string):
return bytes(hashlib.sha512(string.encode()).hexdigest()[:AES_BLOCK_SIZE], 'utf-8')
def _pad(msg):
return msg + (AES_BLOCK_SIZE - len(msg) % AES_BLOCK_SIZE) * chr(AES_BLOCK_SIZE - len(msg) % AES_BLOCK_SIZE)
def _unpad(msg):
return msg[:-ord(msg[len(msg) - 1:])]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment