File size: 6,080 Bytes
cc5c9eb
 
 
 
 
 
 
52de8f8
cc5c9eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
"""
API key encryption and decryption utilities
Provides AES-256-CBC encryption for secure API key handling
"""

import os
import base64
import secrets
from typing import Optional
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend


def encrypt_api_key(raw_key: Optional[str]) -> Optional[str]:
    """
    Encrypt an API key using AES-256-CBC encryption
    
    Args:
        raw_key: The raw API key to encrypt
        
    Returns:
        Base64-encoded encrypted string or None if input is None/empty
        
    Raises:
        ValueError: If encryption configuration is missing or invalid
        Exception: If encryption fails
    """
    # Get encryption configuration from environment
    aes_secret_key = os.getenv('AES_SECRET_KEY')
    aes_iv = os.getenv('AES_IV')
    
    # Check if raw key is valid
    if not raw_key or raw_key.strip() == '':
        return None
    
    # Validate encryption configuration
    if not aes_secret_key or not aes_iv:
        raise ValueError(
            'Missing encryption configuration: AES_SECRET_KEY or AES_IV not found'
        )
    
    try:
        # Convert hex strings to bytes
        key_bytes = bytes.fromhex(aes_secret_key)
        iv_bytes = bytes.fromhex(aes_iv)
        
        # Validate key and IV sizes
        if len(key_bytes) != 32:  # 256 bits
            raise ValueError('AES_SECRET_KEY must be 64 hex characters (32 bytes)')
        if len(iv_bytes) != 16:   # 128 bits
            raise ValueError('AES_IV must be 32 hex characters (16 bytes)')
        
        # Create cipher
        cipher = Cipher(
            algorithms.AES(key_bytes),
            modes.CBC(iv_bytes),
            backend=default_backend()
        )
        encryptor = cipher.encryptor()
        
        # Convert string to bytes and pad to block size
        raw_bytes = raw_key.encode('utf-8')
        padded_data = _pad_data(raw_bytes)
        
        # Encrypt
        encrypted_bytes = encryptor.update(padded_data) + encryptor.finalize()
        
        # Return base64-encoded result
        return base64.b64encode(encrypted_bytes).decode('ascii')
        
    except ValueError as e:
        # Re-raise validation errors
        raise e
    except Exception as e:
        raise Exception(
            f'Failed to encrypt API key: Invalid key format or encryption error - {str(e)}'
        )


def decrypt_api_key(encrypted_key: Optional[str]) -> Optional[str]:
    """
    Decrypt an API key using AES-256-CBC decryption
    
    Args:
        encrypted_key: Base64-encoded encrypted API key
        
    Returns:
        Decrypted API key string or None if input is None/empty
        
    Raises:
        ValueError: If encryption configuration is missing or invalid
        Exception: If decryption fails
    """
    # Get encryption configuration from environment
    aes_secret_key = os.getenv('AES_SECRET_KEY')
    aes_iv = os.getenv('AES_IV')
    
    # Check if encrypted key is valid
    if not encrypted_key or encrypted_key.strip() == '':
        return None
    
    # Validate encryption configuration
    if not aes_secret_key or not aes_iv:
        raise ValueError(
            'Missing encryption configuration: AES_SECRET_KEY or AES_IV not found'
        )
    
    try:
        # Convert hex strings to bytes
        key_bytes = bytes.fromhex(aes_secret_key)
        iv_bytes = bytes.fromhex(aes_iv)
        
        # Validate key and IV sizes
        if len(key_bytes) != 32:  # 256 bits
            raise ValueError('AES_SECRET_KEY must be 64 hex characters (32 bytes)')
        if len(iv_bytes) != 16:   # 128 bits
            raise ValueError('AES_IV must be 32 hex characters (16 bytes)')
        
        # Decode base64
        encrypted_bytes = base64.b64decode(encrypted_key.encode('ascii'))
        
        # Create cipher
        cipher = Cipher(
            algorithms.AES(key_bytes),
            modes.CBC(iv_bytes),
            backend=default_backend()
        )
        decryptor = cipher.decryptor()
        
        # Decrypt
        decrypted_padded = decryptor.update(encrypted_bytes) + decryptor.finalize()
        
        # Remove padding and convert to string
        decrypted_bytes = _unpad_data(decrypted_padded)
        return decrypted_bytes.decode('utf-8')
        
    except ValueError as e:
        # Re-raise validation errors
        raise e
    except Exception as e:
        raise Exception(
            f'Failed to decrypt API key: Invalid key format or corrupted data - {str(e)}'
        )


def _pad_data(data: bytes) -> bytes:
    """
    Pad data to AES block size using PKCS7 padding
    
    Args:
        data: Raw bytes to pad
        
    Returns:
        Padded bytes
    """
    block_size = 16  # AES block size
    padding_length = block_size - (len(data) % block_size)
    padding = bytes([padding_length] * padding_length)
    return data + padding


def _unpad_data(padded_data: bytes) -> bytes:
    """
    Remove PKCS7 padding from data
    
    Args:
        padded_data: Padded bytes
        
    Returns:
        Unpadded bytes
        
    Raises:
        ValueError: If padding is invalid
    """
    if len(padded_data) == 0:
        raise ValueError("Cannot unpad empty data")
    
    padding_length = padded_data[-1]
    
    if padding_length > 16 or padding_length == 0:
        raise ValueError("Invalid padding length")
    
    # Verify padding
    for i in range(padding_length):
        if padded_data[-(i + 1)] != padding_length:
            raise ValueError("Invalid padding")
    
    return padded_data[:-padding_length]


def generate_encryption_keys() -> tuple[str, str]:
    """
    Generate new AES secret key and IV for development/testing purposes
    
    Returns:
        Tuple of (secret_key_hex, iv_hex)
    """
    
    # Generate 32 random bytes for AES-256 key
    secret_key = secrets.token_bytes(32)
    
    # Generate 16 random bytes for IV
    iv = secrets.token_bytes(16)
    
    return secret_key.hex(), iv.hex()