Skip to content

Instantly share code, notes, and snippets.

@leiless
Created April 3, 2024 02:18
Show Gist options
  • Save leiless/c115eb86b78e74e235b98bedefd5d8b5 to your computer and use it in GitHub Desktop.
Save leiless/c115eb86b78e74e235b98bedefd5d8b5 to your computer and use it in GitHub Desktop.
Python: AES-256, CBC mode, PKCS#7 padding
#!/usr/bin/env python3
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding
# https://cryptography.io/en/latest/hazmat/primitives/symmetric-encryption/
# https://cryptography.io/en/latest/hazmat/primitives/padding/#cryptography.hazmat.primitives.padding.PKCS7
class AES256:
KEY_SIZE = 32
BLOCK_SIZE = 16
def __init__(self, secret: bytes, iv: bytes):
assert len(secret) == AES256.KEY_SIZE, f'unexpected secret len {len(secret)}'
assert len(iv) == AES256.BLOCK_SIZE, f'unexpected iv len {len(iv)}'
self._cipher = Cipher(algorithms.AES(secret), modes.CBC(iv))
self._encryptor = self._cipher.encryptor()
self._padder = padding.PKCS7(AES256.BLOCK_SIZE * 8).padder()
self._decryptor = self._cipher.decryptor()
self._unpadder = padding.PKCS7(AES256.BLOCK_SIZE * 8).unpadder()
def encrypt(self, cleartext: bytes) -> bytes:
padded_cleartext = self._padder.update(cleartext) + self._padder.finalize()
return self._encryptor.update(padded_cleartext) + self._encryptor.finalize()
def decrypt(self, ciphertext: bytes) -> bytes:
padded_cleartext = self._decryptor.update(ciphertext) + self._decryptor.finalize()
return self._unpadder.update(padded_cleartext) + self._unpadder.finalize()
def main():
aes256 = AES256(b'\x00' * AES256.KEY_SIZE, b'\x01' * AES256.BLOCK_SIZE)
cleartext = b'hello world'
ciphertext = aes256.encrypt(cleartext)
cleartext2 = aes256.decrypt(ciphertext)
assert cleartext == cleartext2, f'{cleartext} vs {cleartext2}'
if __name__ == '__main__':
main()
@leiless
Copy link
Author

leiless commented Apr 3, 2024

https://cryptography.io/en/latest/
https://pypi.org/project/cryptography

pip3 install cryptography

TODO

  • IV should be different per encryption operation, don't reuse the same IV for each encryption.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment