diff --git a/src/password_manager/encryption.py b/src/password_manager/encryption.py index 40f3b31..db42c6b 100644 --- a/src/password_manager/encryption.py +++ b/src/password_manager/encryption.py @@ -339,11 +339,13 @@ class EncryptionManager: relative_path = Path("seedpass_passwords_db.json.enc") try: file_path = self.fingerprint_dir / relative_path - decrypted_data = self.decrypt_file(relative_path) - content = decrypted_data.decode("utf-8") - logger.debug("Calculating checksum of the updated file content.") + logger.debug("Calculating checksum of the encrypted file bytes.") - checksum = hashlib.sha256(content.encode("utf-8")).hexdigest() + with exclusive_lock(file_path): + with open(file_path, "rb") as f: + encrypted_bytes = f.read() + + checksum = hashlib.sha256(encrypted_bytes).hexdigest() logger.debug(f"New checksum: {checksum}") checksum_file = file_path.parent / f"{file_path.stem}_checksum.txt" diff --git a/src/tests/test_encryption_checksum.py b/src/tests/test_encryption_checksum.py new file mode 100644 index 0000000..0922e8d --- /dev/null +++ b/src/tests/test_encryption_checksum.py @@ -0,0 +1,34 @@ +import re +import sys +from pathlib import Path +from tempfile import TemporaryDirectory + +from cryptography.fernet import Fernet + +sys.path.append(str(Path(__file__).resolve().parents[1])) + +from password_manager.encryption import EncryptionManager +from utils.checksum import verify_and_update_checksum + + +def test_encryption_checksum_workflow(): + with TemporaryDirectory() as tmpdir: + tmp_path = Path(tmpdir) + key = Fernet.generate_key() + manager = EncryptionManager(key, tmp_path) + + data = {"value": 1} + manager.save_json_data(data) + manager.update_checksum() + + enc_file = tmp_path / "seedpass_passwords_db.json.enc" + chk_file = tmp_path / "seedpass_passwords_db.json_checksum.txt" + + checksum = chk_file.read_text().strip() + assert re.fullmatch(r"[0-9a-f]{64}", checksum) + + manager.save_json_data({"value": 2}) + assert not verify_and_update_checksum(str(enc_file), str(chk_file)) + + manager.update_checksum() + assert verify_and_update_checksum(str(enc_file), str(chk_file))