diff --git a/src/password_manager/encryption.py b/src/password_manager/encryption.py index 32731a6..38da332 100644 --- a/src/password_manager/encryption.py +++ b/src/password_manager/encryption.py @@ -89,6 +89,9 @@ class EncryptionManager: try: nonce = encrypted_data[3:15] ciphertext = encrypted_data[15:] + if len(ciphertext) < 16: + logger.error("AES-GCM payload too short") + raise InvalidToken("AES-GCM payload too short") return self.cipher.decrypt(nonce, ciphertext, None) except InvalidTag as e: logger.error("AES-GCM decryption failed: Invalid authentication tag.") diff --git a/src/tests/test_v2_prefix_fallback.py b/src/tests/test_v2_prefix_fallback.py index 6082485..0d23cbf 100644 --- a/src/tests/test_v2_prefix_fallback.py +++ b/src/tests/test_v2_prefix_fallback.py @@ -1,6 +1,10 @@ import logging +import os from pathlib import Path +import pytest +from cryptography.fernet import InvalidToken + from helpers import TEST_SEED from utils.key_derivation import derive_index_key from password_manager.encryption import EncryptionManager @@ -19,3 +23,16 @@ def test_v2_prefix_fernet_fallback(tmp_path: Path, caplog) -> None: assert decrypted == original assert "incorrect 'V2:' header" in caplog.text + + +def test_aesgcm_payload_too_short(tmp_path: Path, caplog) -> None: + key = derive_index_key(TEST_SEED) + manager = EncryptionManager(key, tmp_path) + + payload = b"V2:" + os.urandom(12) + b"short" + + caplog.set_level(logging.ERROR, logger="password_manager.encryption") + with pytest.raises(InvalidToken, match="AES-GCM payload too short"): + manager.decrypt_data(payload) + + assert "AES-GCM payload too short" in caplog.text