Spaces:
Sleeping
Sleeping
from Crypto.Cipher import AES | |
from Crypto.Protocol.SecretSharing import Shamir | |
from Crypto.Random import get_random_bytes | |
from Crypto.Util.Padding import unpad | |
from base64 import b64decode | |
def decrypt(ciphertext_iv_hex: str, key: bytes): | |
""" | |
Decrypts data encrypted using Web Crypto API with AES-GCM in Python. | |
Args: | |
ciphertext_iv_hex (str): Encrypted data as hex string, in format "IV.CIPHERTEXT". | |
key (bytes): The decryption key as a byte array. | |
Returns: | |
str: The decrypted plaintext message. | |
""" | |
try: | |
# Split IV and ciphertext from hex string | |
iv_hex, ciphertext_hex = ciphertext_iv_hex.split(".") | |
iv_bytes = bytes.fromhex(iv_hex) | |
# print([b for b in iv_bytes]) | |
ciphertext_bytes = bytes.fromhex(ciphertext_hex) | |
# print([b for b in ciphertext_bytes]) | |
# Create AES-GCM cipher object with 128-bit tag (for compatibility with Web Crypto) | |
cipher = AES.new(key, AES.MODE_CBC, iv=iv_bytes) | |
# Decrypt the ciphertext (assuming authentication is handled elsewhere) | |
decrypted_bytes = cipher.decrypt(ciphertext_bytes) | |
# decrypted_text = unpad(decrypted_bytes, AES.block_size) | |
# print("Decrypted ggg:", decrypted_text) | |
# cb = [b for b in decrypted_bytes] | |
print("Decrypted bytes:", decrypted_bytes.replace(b"\x05", b"")) | |
decrypted_text = decrypted_bytes.decode("utf-8") # Assuming UTF-8 encoding | |
return decrypted_text | |
except ValueError as e: | |
print("Decryption error:", e) | |
return None # Return None on decryption failure | |
# Example usage | |
key = b"YourSecretKey1234"[:16] # Keep this key secure! | |
encrypted_data = "714fd62d80c40154f87d1d174b1d01bf.ca73441f070a344512f85474372e7329ec01722a4a28699218f9bcd13bc81c3d87c80e4b81859f39df70917b54fc6df38bb222d749e5d20c5e1687dbc20956fb" # Get this from JavaScript | |
decrypted_text = decrypt(encrypted_data, key) | |
print("Decrypted message:", decrypted_text) | |
print("http://localhost:3000/uploads/photo_2024-03-19_01-44-38.jpg".encode()) | |