Created
April 3, 2024 02:18
-
-
Save leiless/c115eb86b78e74e235b98bedefd5d8b5 to your computer and use it in GitHub Desktop.
Python: AES-256, CBC mode, PKCS#7 padding
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
#!/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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://cryptography.io/en/latest/
https://pypi.org/project/cryptography
TODO