Spaces:
Sleeping

File size: 3,036 Bytes
41582e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# 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