Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
AES256 encryption using pyca/cryptography
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