|
| 1 | +""" |
| 2 | +Secure encryption module for handling password-based encryption. |
| 3 | +
|
| 4 | +This module provides functions for: |
| 5 | +- Generating secure salts |
| 6 | +- Deriving encryption keys from passwords using PBKDF2-HMAC-SHA256 |
| 7 | +- Encrypting and decrypting data using Fernet (AES-128 in CBC mode) |
| 8 | +- Managing master keys for encryption |
| 9 | +""" |
| 10 | + |
| 11 | +import os |
| 12 | +from base64 import urlsafe_b64encode |
| 13 | +from pathlib import Path |
| 14 | + |
| 15 | +from cryptography.hazmat.primitives import hashes |
| 16 | +from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC |
| 17 | +from cryptography.fernet import Fernet, InvalidToken |
| 18 | + |
| 19 | +from .errors import KeyDerivationError, EncryptionError, DecryptionError |
| 20 | + |
| 21 | +DEFAULT_SALT_LENGTH = 16 |
| 22 | +DEFAULT_ITERATIONS = 100_000 |
| 23 | +MIN_ITERATIONS = 10_000 |
| 24 | +KEY_LENGTH = 32 # 256 bits for AES-256 |
| 25 | + |
| 26 | + |
| 27 | +def generate_salt(length: int = DEFAULT_SALT_LENGTH) -> bytes: |
| 28 | + """ |
| 29 | + Generate a cryptographic salt. |
| 30 | +
|
| 31 | + Args: |
| 32 | + length (int): Length of the salt in bytes. Default is 16 bytes. |
| 33 | +
|
| 34 | + Returns: |
| 35 | + Random salt bytes |
| 36 | +
|
| 37 | + Raises: |
| 38 | + ValueError: If length is less than 8 bytes. |
| 39 | + """ |
| 40 | + if length <= 8: |
| 41 | + raise ValueError("Salt length must be a positive integer.") |
| 42 | + |
| 43 | + return os.urandom(length) |
| 44 | + |
| 45 | + |
| 46 | +def derive_key_from_password( |
| 47 | + password: str, salt: bytes, iterations: int = DEFAULT_ITERATIONS |
| 48 | +) -> bytes: |
| 49 | + """ |
| 50 | + Derive an encryption key from a password using PBKDF2-HMAC-SHA256. |
| 51 | +
|
| 52 | + Args: |
| 53 | + password: User password |
| 54 | + salt: Random salt for key derivation |
| 55 | + iterations: Number of PBKDF2 iterations (default: 100,000) |
| 56 | +
|
| 57 | + Returns: |
| 58 | + Derived key bytes |
| 59 | +
|
| 60 | + Raises: |
| 61 | + ValueError: If password is empty or iterations < 10000 |
| 62 | + KeyDerivationError: If key derivation fails |
| 63 | + """ |
| 64 | + if not password: |
| 65 | + raise ValueError("Password cannot be empty") |
| 66 | + |
| 67 | + if iterations < MIN_ITERATIONS: |
| 68 | + raise ValueError(f"Iterations must be at least {MIN_ITERATIONS}") |
| 69 | + |
| 70 | + try: |
| 71 | + kdf = PBKDF2HMAC( |
| 72 | + algorithm=hashes.SHA256(), |
| 73 | + length=KEY_LENGTH, |
| 74 | + salt=salt, |
| 75 | + iterations=iterations, |
| 76 | + ) |
| 77 | + |
| 78 | + key = kdf.derive(password.encode("utf-8")) |
| 79 | + return urlsafe_b64encode(key) |
| 80 | + except Exception as e: |
| 81 | + raise KeyDerivationError(f"Failed to derive key: {e}") from e |
| 82 | + |
| 83 | + |
| 84 | +def encrypt_bytes(key: bytes, plaintext: bytes) -> bytes: |
| 85 | + """ |
| 86 | + Encrypt plaintext bytes using Fernet (AES-128 in CBC mode). |
| 87 | +
|
| 88 | + Args: |
| 89 | + key: Base64-encoded encryption key (from derive_key_from_password) |
| 90 | + plaintext: Data to encrypt |
| 91 | +
|
| 92 | + Returns: |
| 93 | + Encrypted token (includes IV and MAC) |
| 94 | +
|
| 95 | + Raises: |
| 96 | + EncryptionError: If encryption fails |
| 97 | + ValueError: If key format is invalid |
| 98 | + """ |
| 99 | + if not plaintext: |
| 100 | + raise ValueError("Plaintext cannot be empty") |
| 101 | + |
| 102 | + try: |
| 103 | + cipher = Fernet(key) |
| 104 | + return cipher.encrypt(plaintext) |
| 105 | + except ValueError as e: |
| 106 | + raise ValueError(f"Invalid key format: {e}") from e |
| 107 | + except Exception as e: |
| 108 | + raise EncryptionError(f"Encryption failed: {e}") from e |
| 109 | + |
| 110 | + |
| 111 | +def decrypt_bytes(key: bytes, token: bytes) -> bytes: |
| 112 | + """ |
| 113 | + Decrypt a Fernet token. |
| 114 | +
|
| 115 | + Args: |
| 116 | + key: Base64-encoded encryption key (same as used for encryption) |
| 117 | + token: Encrypted token to decrypt |
| 118 | +
|
| 119 | + Returns: |
| 120 | + Decrypted plaintext bytes |
| 121 | +
|
| 122 | + Raises: |
| 123 | + DecryptionError: If decryption fails (wrong key or corrupted data) |
| 124 | + ValueError: If key format is invalid |
| 125 | + """ |
| 126 | + if not token: |
| 127 | + raise ValueError("Token cannot be empty") |
| 128 | + |
| 129 | + try: |
| 130 | + cipher = Fernet(key) |
| 131 | + return cipher.decrypt(token) |
| 132 | + except InvalidToken: |
| 133 | + raise DecryptionError("Decryption failed: incorrect passowrd or corrupted data") |
| 134 | + except ValueError as e: |
| 135 | + raise ValueError(f"Invalid key format: {e}") from e |
| 136 | + except Exception as e: |
| 137 | + raise DecryptionError(f"Decryption failed: {e}") from e |
| 138 | + |
| 139 | + |
| 140 | +def encrypt_text(key: bytes, plaintext: str) -> bytes: |
| 141 | + """ |
| 142 | + Encrypt a text string. |
| 143 | +
|
| 144 | + Args: |
| 145 | + key: Base64-encoded encryption key |
| 146 | + plaintext: Text to encrypt |
| 147 | +
|
| 148 | + Returns: |
| 149 | + Encrypted token |
| 150 | + """ |
| 151 | + return encrypt_bytes(key, plaintext.encode("utf-8")) |
| 152 | + |
| 153 | + |
| 154 | +def decrypt_text(key: bytes, token: bytes) -> str: |
| 155 | + """ |
| 156 | + Decrypt a token to text string. |
| 157 | +
|
| 158 | + Args: |
| 159 | + key: Base64-encoded encryption key |
| 160 | + token: Encrypted token |
| 161 | +
|
| 162 | + Returns: |
| 163 | + Decrypted text |
| 164 | + """ |
| 165 | + plaintext_bytes = decrypt_bytes(key, token) |
| 166 | + return plaintext_bytes.decode("utf-8") |
| 167 | + |
| 168 | + |
| 169 | +def generate_master_key() -> bytes: |
| 170 | + """ |
| 171 | + Generate a random Fernet-compatible master key. |
| 172 | +
|
| 173 | + This can be used instead of password-based encryption for scenarios |
| 174 | + where you want to generate and store a random key. |
| 175 | +
|
| 176 | + Returns: |
| 177 | + Base64-encoded random key |
| 178 | + """ |
| 179 | + return Fernet.generate_key() |
| 180 | + |
| 181 | + |
| 182 | +def save_master_key(key: bytes, filepath: Path | str) -> None: |
| 183 | + """ |
| 184 | + Save a master key to a file with secure permissions. |
| 185 | +
|
| 186 | + Args: |
| 187 | + key: Base64-encoded key to save |
| 188 | + filepath: Path to save the key |
| 189 | +
|
| 190 | + Raises: |
| 191 | + OSError: If file operations fail |
| 192 | + """ |
| 193 | + filepath = Path(filepath) |
| 194 | + |
| 195 | + filepath.parent.mkdir(parents=True, exist_ok=True) |
| 196 | + filepath.write_bytes(key) |
| 197 | + |
| 198 | + try: |
| 199 | + os.chmod(filepath, 0o600) |
| 200 | + except (AttributeError, OSError): |
| 201 | + print(f"Warning: Could not set secure permissions on {filepath}") |
| 202 | + |
| 203 | + |
| 204 | +def load_master_key(filepath: Path | str) -> bytes: |
| 205 | + """ |
| 206 | + Load a master key from a file. |
| 207 | +
|
| 208 | + Args: |
| 209 | + filepath: Path to the key file |
| 210 | +
|
| 211 | + Returns: |
| 212 | + Base64-encoded key |
| 213 | +
|
| 214 | + Raises: |
| 215 | + FileNotFoundError: If key file doesn't exist |
| 216 | + ValueError: If key format is invalid |
| 217 | + """ |
| 218 | + filepath = Path(filepath) |
| 219 | + |
| 220 | + if not filepath.exists(): |
| 221 | + raise FileNotFoundError(f"Key file not found: {filepath}") |
| 222 | + |
| 223 | + key = filepath.read_bytes().strip() |
| 224 | + |
| 225 | + try: |
| 226 | + Fernet(key) |
| 227 | + except Exception as e: |
| 228 | + raise ValueError(f"Invalid key format in {filepath}: {e}") from e |
| 229 | + |
| 230 | + return key |
| 231 | + |
| 232 | + |
| 233 | +def verify_password(password: str, salt: bytes, encrypted_data: bytes) -> bool: |
| 234 | + """ |
| 235 | + Verify if a password is correct by attempting to decrypt data. |
| 236 | +
|
| 237 | + Args: |
| 238 | + password: Password to verify |
| 239 | + salt: Salt used for key derivation |
| 240 | + encrypted_data: Sample encrypted data to test |
| 241 | +
|
| 242 | + Returns: |
| 243 | + True if password is correct, False otherwise |
| 244 | + """ |
| 245 | + try: |
| 246 | + key = derive_key_from_password(password, salt) |
| 247 | + decrypt_bytes(key, encrypted_data) |
| 248 | + return True |
| 249 | + except (DecryptionError, KeyDerivationError): |
| 250 | + return False |
0 commit comments