import { extractErrorMsg, hash, HashAlgorithm } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs'; import { GLOBAL_LOG_A_LOT } from '../../core-constants.mjs'; import { KDF_STRATEGY_RECURSIVE_SALT_WRAP, KDF_STRATEGY_VALID_VALUES, KdfStrategy } from './kdf-constants.mjs'; import { DeriveKeyParams, KdfOptions_RecursiveSaltWrap } from './kdf-types.mjs'; const logalot = GLOBAL_LOG_A_LOT; /** * Derive a key from a master secret using the specified KDF strategy * * This is the main dispatch function for all KDF operations. It routes to the * appropriate strategy implementation based on `kdfOpts.strategy`. * * @param params - Derivation parameters including master secret and KDF options * @returns Derived key * * @example * ```typescript * const derivedKey = await deriveKey({ * masterSecret: 'my-strong-password', * kdfOpts: { * strategy: KdfStrategy.recursiveSaltWrap, * salt: 'pool-identifier', * rounds: 10000, * algorithm: 'SHA-256' * } * }); * ``` */ export async function deriveKey({ masterSecret, kdfOpts }: DeriveKeyParams): Promise { const lc = `[${deriveKey.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: 268e87ec311874ee6822bf459c5a5426)`); } const strategy = kdfOpts.strategy; switch (strategy) { case KdfStrategy.recursive_salt_wrap: return await kdf_recursiveSaltWrap({ masterSecret, salt: kdfOpts.salt, rounds: kdfOpts.rounds, algorithm: kdfOpts.algorithm }); default: throw new Error(`Unknown KDF strategy: ${strategy}. valid values: ${KDF_STRATEGY_VALID_VALUES.join(', ')} (E: c81258e9d9481eb0f88385a825193226)`); } } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } /** * Recursive Salt Wrap KDF Strategy * * Derives a key by recursively applying: Hash(salt + current + salt) for N rounds * * This is the strategy used by KeystoneStrategy_HashRevealV1 for deriving pool secrets. * * @param masterSecret - The initial secret/password to derive from * @param salt - Salt value to wrap around the secret * @param rounds - Number of hash iterations (key stretching) * @param algorithm - Hash algorithm to use (default: SHA-256) * @returns Derived key */ export async function kdf_recursiveSaltWrap({ masterSecret, salt, rounds, algorithm = HashAlgorithm.sha_256, }: { masterSecret: string; salt: string; rounds: number; algorithm?: HashAlgorithm; }): Promise { const lc = `[${kdf_recursiveSaltWrap.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: 850868e50aba82ff28c77da8169e4c26)`); } let current = masterSecret; for (let i = 0; i < rounds; i++) { current = await hash({ s: `${salt}${current}${salt}`, algorithm }); } return current; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } }