# encryption_utils.py import base64 from Crypto.Cipher import AES from Crypto.Util.Padding import pad, unpad from Crypto.Random import get_random_bytes # AES key in URL-safe Base64 format. # This MUST match the key used by the Flutter frontend. RAW_KEY_B64 = "KqkSHMHRWxjeMj-72YCOn1AJLleiAlyFGZIEjgMY5iY=" def _decode_key() -> bytes: """ Decode the URL-safe Base64 AES key. """ try: safe_key_b64 = ( RAW_KEY_B64 .replace("-", "+") .replace("_", "/") ) padded_key_b64 = ( safe_key_b64 + "=" * ((4 - len(safe_key_b64) % 4) % 4) ) decoded_key = base64.b64decode( padded_key_b64 ) if len(decoded_key) not in (16, 24, 32): raise ValueError( f"Invalid AES key length: {len(decoded_key)} bytes" ) return decoded_key except Exception as e: print(f"Error decoding AES key: {e}") raise KEY = _decode_key() def encrypt_message(message: str) -> str: """ Encrypt a UTF-8 message using AES-CBC. Format: Base64(IV + ciphertext) This format matches the Flutter implementation. """ try: if message is None: raise ValueError("Message cannot be None") message = str(message) # Generate a fresh 16-byte IV for every message. iv = get_random_bytes(16) cipher = AES.new( KEY, AES.MODE_CBC, iv, ) padded = pad( message.encode("utf-8"), AES.block_size, ) encrypted = cipher.encrypt(padded) # Flutter expects: # IV + encrypted data combined = iv + encrypted return base64.b64encode( combined ).decode("utf-8") except Exception as e: print(f"Encryption error: {e}") raise def decrypt_message(token: str) -> str: """ Decrypt a Base64(IV + ciphertext) AES-CBC message. """ try: if not token: raise ValueError( "Encrypted token cannot be empty" ) raw = base64.b64decode(token) # Minimum: # 16 bytes IV + at least 16 bytes ciphertext if len(raw) < 32: raise ValueError( "Invalid encrypted message" ) # First 16 bytes = IV iv = raw[:16] # Remaining bytes = ciphertext ciphertext = raw[16:] if len(ciphertext) % AES.block_size != 0: raise ValueError( "Invalid ciphertext length" ) cipher = AES.new( KEY, AES.MODE_CBC, iv, ) decrypted = cipher.decrypt( ciphertext ) unpadded = unpad( decrypted, AES.block_size, ) return unpadded.decode("utf-8") except Exception as e: print(f"Decryption error: {e}") raise