Spaces:
Running
Running
File size: 1,003 Bytes
3ce4cf9 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | import os
import hashlib
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
# ===== Key (same idea as Node) =====
def get_key():
raw_key = os.environ["TOKEN_KEY_ENCRYPTION"].encode()
return hashlib.sha256(raw_key).digest() # 32 bytes
# ===== Encrypt =====
def encrypt_token_to_json(token: str) -> dict:
key = get_key()
aesgcm = AESGCM(key)
iv = os.urandom(12) # same as crypto.randomBytes(12)
encrypted = aesgcm.encrypt(iv, token.encode(), None)
ciphertext = encrypted[:-16]
tag = encrypted[-16:]
return {
"iv": iv.hex(),
"data": ciphertext.hex(),
"tag": tag.hex(),
}
# ===== Decrypt =====
def decrypt_token_from_json(enc: dict) -> str:
key = get_key()
aesgcm = AESGCM(key)
iv = bytes.fromhex(enc["iv"])
ciphertext = bytes.fromhex(enc["data"])
tag = bytes.fromhex(enc["tag"])
encrypted = ciphertext + tag
decrypted = aesgcm.decrypt(iv, encrypted, None)
return decrypted.decode()
|