| 26 | |
| 27 | # Start of Decryption Function |
| 28 | def decrypt(enc_dict, password): |
| 29 | if not password: |
| 30 | raise ValueError("Password cannot be empty.") |
| 31 | |
| 32 | try: |
| 33 | salt = b64decode(enc_dict["salt"]) |
| 34 | cipher_text = b64decode(enc_dict["cipher_text"]) |
| 35 | nonce = b64decode(enc_dict["nonce"]) |
| 36 | tag = b64decode(enc_dict["tag"]) |
| 37 | private_key = hashlib.scrypt( |
| 38 | password.encode(), salt=salt, n=2**14, r=8, p=1, dklen=32 |
| 39 | ) |
| 40 | cipher = AES.new(private_key, AES.MODE_GCM, nonce=nonce) |
| 41 | decrypted = cipher.decrypt_and_verify(cipher_text, tag) |
| 42 | return decrypted.decode("utf-8") |
| 43 | except (ValueError, KeyError) as e: |
| 44 | raise ValueError("Invalid encrypted message format.") from e |
| 45 | |
| 46 | |
| 47 | def main(): |