Created
October 11, 2018 00:49
-
-
Save Sen-Zhang/50a8109fc944424e9ead6102d56c8a6e to your computer and use it in GitHub Desktop.
AES Cipher in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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