Last active
April 17, 2023 17:52
-
-
Save brysontyrrell/7cebfb05105c25d00e84ed35bd821dfe to your computer and use it in GitHub Desktop.
AES256 encryption using pyca/cryptography
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 os | |
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes | |
from cryptography.hazmat.backends import default_backend | |
class AESCipher(object): | |
block_size = algorithms.AES.block_size / 8 | |
def __init__(self, key): | |
if len(key) * 8 != 256: | |
raise ValueError('Invalid key size (must be 256 bit)') | |
self._key = key | |
def _cipher(self, iv): | |
return Cipher( | |
algorithms.AES(self._key), | |
modes.CBC(iv), | |
backend=default_backend() | |
) | |
def encrypt(self, raw): | |
iv = os.urandom(AESCipher.block_size) | |
encryptor = self._cipher(iv).encryptor() | |
padded = self._pad(raw) | |
cipher_text = encryptor.update(padded) + encryptor.finalize() | |
return base64.b64encode(cipher_text + iv) | |
def decrypt(self, encoded): | |
raw = base64.b64decode(encoded) | |
cipher_text = raw[:-AESCipher.block_size] | |
iv = raw[-AESCipher.block_size:] | |
decryptor = self._cipher(iv).decryptor() | |
padded = decryptor.update(cipher_text) + decryptor.finalize() | |
return self._unpad(padded) | |
def _pad(raw): | |
ordinal = AESCipher.block_size - len(raw) % AESCipher.block_size | |
return raw + ordinal * chr(ordinal) | |
@staticmethod | |
def _unpad(padded): | |
return padded[:-ord(padded[len(padded) - 1:])] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment