| 8 | |
| 9 | |
| 10 | class CipherManager: |
| 11 | def __init__(self, config: Config): |
| 12 | self.config = config |
| 13 | |
| 14 | # hash |
| 15 | self.hash_name = "sha256" |
| 16 | self.dklen = 32 # 256 bits for AES-256 |
| 17 | |
| 18 | # encryption |
| 19 | self.mode = AES.MODE_GCM |
| 20 | |
| 21 | def hash_password(self, password: str) -> bytes: |
| 22 | return hashlib.pbkdf2_hmac( |
| 23 | hash_name=self.hash_name, |
| 24 | password=password.encode(), |
| 25 | salt=( |
| 26 | self.config.data["username"] + password + self.config.data["salt"] |
| 27 | ).encode("utf-8"), |
| 28 | iterations=self.config.data["hash_rounds"], |
| 29 | dklen=self.dklen, |
| 30 | ) |
| 31 | |
| 32 | def encrypt(self, plaintext: str) -> dict: |
| 33 | key = self.config.data["hashed_password"] |
| 34 | plaintext_bytes = plaintext.encode("utf-8") |
| 35 | cipher = AES.new(key, self.mode) |
| 36 | ciphertext, tag = cipher.encrypt_and_digest(plaintext_bytes) |
| 37 | return {"nonce": cipher.nonce, "ciphertext": ciphertext, "tag": tag} |
| 38 | |
| 39 | def decrypt(self, nonce: bytes, ciphertext: bytes, tag: bytes) -> str: |
| 40 | key = self.config.data["hashed_password"] |
| 41 | cipher = AES.new(key, self.mode, nonce=nonce) |
| 42 | return cipher.decrypt_and_verify(ciphertext, tag).decode() |
| 43 | |
| 44 | @staticmethod |
| 45 | def encode_to_json_string(**kwargs: bytes) -> str: |
| 46 | """ |
| 47 | Convert bytes values to Base64 and create a JSON string. |
| 48 | |
| 49 | Args: |
| 50 | **kwargs: Key-value pairs where values must be of type `bytes`. |
| 51 | |
| 52 | Returns: |
| 53 | str: A JSON string with all `bytes` values Base64-encoded. |
| 54 | |
| 55 | Raises: |
| 56 | ValueError: If a value is not of type `bytes`. |
| 57 | """ |
| 58 | json_data = {} |
| 59 | for key, value in kwargs.items(): |
| 60 | if isinstance(value, bytes): |
| 61 | json_data[key] = base64.b64encode(value).decode("utf-8") |
| 62 | else: |
| 63 | raise ValueError( |
| 64 | f"Unsupported value type for key '{key}': {type(value)}. " |
| 65 | f"This method only supports 'bytes'." |
| 66 | ) |
| 67 | return json.dumps(json_data) |