|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import os |
| 4 | +from base64 import b64decode, b64encode |
| 5 | +from typing import TYPE_CHECKING |
| 6 | + |
| 7 | +from cryptography.exceptions import InvalidTag |
| 8 | +from cryptography.hazmat.primitives.ciphers.aead import AESGCM |
| 9 | + |
| 10 | +from eventsourcing.persistence import Cipher |
| 11 | + |
| 12 | +if TYPE_CHECKING: |
| 13 | + from eventsourcing.utils import Environment |
| 14 | + |
| 15 | + |
| 16 | +class AESCipher(Cipher): |
| 17 | + """ |
| 18 | + Cipher strategy that uses AES cipher (in GCM mode) |
| 19 | + from the Python cryptography package. |
| 20 | + """ |
| 21 | + |
| 22 | + CIPHER_KEY = "CIPHER_KEY" |
| 23 | + KEY_SIZES = (16, 24, 32) |
| 24 | + |
| 25 | + @staticmethod |
| 26 | + def create_key(num_bytes: int) -> str: |
| 27 | + """ |
| 28 | + Creates AES cipher key, with length num_bytes. |
| 29 | +
|
| 30 | + :param num_bytes: An int value, either 16, 24, or 32. |
| 31 | +
|
| 32 | + """ |
| 33 | + AESCipher.check_key_size(num_bytes) |
| 34 | + key = AESGCM.generate_key(num_bytes * 8) |
| 35 | + return b64encode(key).decode("utf8") |
| 36 | + |
| 37 | + @staticmethod |
| 38 | + def check_key_size(num_bytes: int) -> None: |
| 39 | + if num_bytes not in AESCipher.KEY_SIZES: |
| 40 | + msg = f"Invalid key size: {num_bytes} not in {AESCipher.KEY_SIZES}" |
| 41 | + raise ValueError(msg) |
| 42 | + |
| 43 | + @staticmethod |
| 44 | + def random_bytes(num_bytes: int) -> bytes: |
| 45 | + return os.urandom(num_bytes) |
| 46 | + |
| 47 | + def __init__(self, environment: Environment): |
| 48 | + """ |
| 49 | + Initialises AES cipher with ``cipher_key``. |
| 50 | +
|
| 51 | + :param str cipher_key: 16, 24, or 32 bytes encoded as base64 |
| 52 | + """ |
| 53 | + cipher_key = environment.get(self.CIPHER_KEY) |
| 54 | + if not cipher_key: |
| 55 | + msg = f"'{self.CIPHER_KEY}' not in env" |
| 56 | + raise OSError(msg) |
| 57 | + key = b64decode(cipher_key.encode("utf8")) |
| 58 | + AESCipher.check_key_size(len(key)) |
| 59 | + self.key = key |
| 60 | + |
| 61 | + def encrypt(self, plaintext: bytes) -> bytes: |
| 62 | + """Return ciphertext for given plaintext.""" |
| 63 | + |
| 64 | + # Construct AES-GCM cipher, with 96-bit nonce. |
| 65 | + aesgcm = AESGCM(self.key) |
| 66 | + nonce = AESCipher.random_bytes(12) |
| 67 | + res = aesgcm.encrypt(nonce, plaintext, None) |
| 68 | + # Put tag at the front for compatibility with eventsourcing.crypto.AESCipher. |
| 69 | + tag = res[-16:] |
| 70 | + encrypted = res[:-16] |
| 71 | + return nonce + tag + encrypted |
| 72 | + |
| 73 | + def decrypt(self, ciphertext: bytes) -> bytes: |
| 74 | + """Return plaintext for given ciphertext.""" |
| 75 | + |
| 76 | + # Split out the nonce, tag, and encrypted data. |
| 77 | + nonce = ciphertext[:12] |
| 78 | + if len(nonce) != 12: |
| 79 | + msg = "Damaged cipher text: invalid nonce length" |
| 80 | + raise ValueError(msg) |
| 81 | + |
| 82 | + # Expect tag at the front. |
| 83 | + tag = ciphertext[12:28] |
| 84 | + if len(tag) != 16: |
| 85 | + msg = "Damaged cipher text: invalid tag length" |
| 86 | + raise ValueError(msg) |
| 87 | + encrypted = ciphertext[28:] |
| 88 | + |
| 89 | + aesgcm = AESGCM(self.key) |
| 90 | + try: |
| 91 | + plaintext = aesgcm.decrypt(nonce, encrypted + tag, None) |
| 92 | + except InvalidTag as e: |
| 93 | + msg = "Invalid cipher tag" |
| 94 | + raise ValueError(msg) from e |
| 95 | + # Decrypt and verify. |
| 96 | + return plaintext |
0 commit comments