Add EncryptionMode enum and integrate index key derivation

This commit is contained in:
thePR0M3TH3AN
2025-07-01 11:01:22 -04:00
parent 32b0e42185
commit f49daca4df
4 changed files with 84 additions and 8 deletions

View File

@@ -20,7 +20,8 @@ import base64
import unicodedata
import logging
import traceback
from typing import Union
from enum import Enum
from typing import Optional, Union
from bip_utils import Bip39SeedGenerator
from local_bip85.bip85 import BIP85
@@ -36,6 +37,17 @@ from cryptography.hazmat.backends import default_backend
logger = logging.getLogger(__name__)
class EncryptionMode(Enum):
"""Supported key derivation modes for database encryption."""
SEED_ONLY = "seed-only"
SEED_PLUS_PW = "seed+pw"
PW_ONLY = "pw-only"
DEFAULT_ENCRYPTION_MODE = EncryptionMode.SEED_ONLY
def derive_key_from_password(password: str, iterations: int = 100_000) -> bytes:
"""
Derives a Fernet-compatible encryption key from the provided password using PBKDF2-HMAC-SHA256.
@@ -196,3 +208,22 @@ def derive_index_key_seed_plus_pw(seed: str, password: str) -> bytes:
)
key = hkdf.derive(seed_bytes + b"|" + pw_bytes)
return base64.urlsafe_b64encode(key)
def derive_index_key(
seed: str,
password: Optional[str] = None,
mode: EncryptionMode = DEFAULT_ENCRYPTION_MODE,
) -> bytes:
"""Derive the index encryption key based on the selected mode."""
if mode == EncryptionMode.SEED_ONLY:
return derive_index_key_seed_only(seed)
if mode == EncryptionMode.SEED_PLUS_PW:
if password is None:
raise ValueError("Password required for seed+pw mode")
return derive_index_key_seed_plus_pw(seed, password)
if mode == EncryptionMode.PW_ONLY:
if password is None:
raise ValueError("Password required for pw-only mode")
return derive_key_from_password(password)
raise ValueError(f"Unsupported encryption mode: {mode}")