Set pbkdf2Encode rounds to default to 210,000 (#1983)

* Set pbkdf2Encode rounds to default to 210,000

* Cap amount of rounds to 2048 when onlyJS = true to prevent overflow issues.

* Patch tests to use a consistent amount of encoding rounds.

* lint

* Add additional docs

* lint

---------

Co-authored-by: Valentin Fernandez <tinchofernandez8@gmail.com>
This commit is contained in:
Tarik Gul
2025-08-20 12:55:25 -03:00
committed by GitHub
co-authored by Valentin Fernandez
parent 55a3201bd5
commit e5e6bdd814
15 changed files with 88 additions and 43 deletions
@@ -39,14 +39,14 @@ describe('hdEthereum', (): void => {
]);
it('derives the right key pair from a mnemonic', (): void => {
const key = hdEthereum(mnemonicToLegacySeed(PHRASE, '', false, 64));
const key = hdEthereum(mnemonicToLegacySeed(PHRASE, '', false, 64, 2048));
expect(key.publicKey).toEqual(PUBLIC);
expect(key.secretKey).toEqual(SECRET);
});
it('derives the right key pair from a mnemonic and a derivation path', (): void => {
const key = hdEthereum(mnemonicToLegacySeed(PHRASE, '', false, 64), derivationPath);
const key = hdEthereum(mnemonicToLegacySeed(PHRASE, '', false, 64, 2048), derivationPath);
expect(key.publicKey).toEqual(PUBLICDERIVED);
expect(key.secretKey).toEqual(SECRETDERIVED);
@@ -54,7 +54,7 @@ describe('ledgerDerive', (): void => {
tests.forEach(({ ed25519, index: [account, address], mnemonic }, index): void => {
it(`derives a known ed25519 seed for ${network} (${index})`, (): void => {
expect(u8aToHex(
hdLedger(mnemonic, `m/44'/${slip44}'/${account}'/0'/${address}'`)
hdLedger(mnemonic, `m/44'/${slip44}'/${account}'/0'/${address}'`, 2048)
.secretKey
.slice(0, 32)
)).toEqual(ed25519);
+2 -2
View File
@@ -9,7 +9,7 @@ import { HARDENED, hdValidatePath } from '../validatePath.js';
import { ledgerDerivePrivate } from './derivePrivate.js';
import { ledgerMaster } from './master.js';
export function hdLedger (_mnemonic: string, path: string): Keypair {
export function hdLedger (_mnemonic: string, path: string, rounds?: number): Keypair {
const words = _mnemonic
.split(' ')
.map((s) => s.trim())
@@ -30,7 +30,7 @@ export function hdLedger (_mnemonic: string, path: string): Keypair {
}
const parts = path.split('/').slice(1);
let seed = ledgerMaster(mnemonic, password);
let seed = ledgerMaster(mnemonic, password, rounds);
for (const p of parts) {
const n = parseInt(p.replace(/'$/, ''), 10);
@@ -13,7 +13,7 @@ const XPRV = '0x402b03cd9c8bed9ba9f9bd6cd9c315ce9fcc59c7c25d37c85a36096617e69d41
describe('ledgerDerive', (): void => {
it('derives a known master xprv', (): void => {
expect(u8aToHex(
ledgerMaster(MNEMONIC)
ledgerMaster(MNEMONIC, undefined, 2048)
)).toEqual(XPRV);
});
});
+11 -3
View File
@@ -8,9 +8,17 @@ import { mnemonicToSeedSync } from '../../mnemonic/bip39.js';
const ED25519_CRYPTO = 'ed25519 seed';
// gets an xprv from a mnemonic
export function ledgerMaster (mnemonic: string, password?: string): Uint8Array {
const seed = mnemonicToSeedSync(mnemonic, password);
/**
* Gets an xprv from a mnemonic
*
* @param mnemonic - The BIP-39 mnemonic phrase to derive the secret from.
* @param password - Optional: password to secure the seed (default: empty string).
* @param wordlist - Optional custom wordlist for mnemonic.
* @param onlyJs - Optional: If `true`, forces use of the JavaScript implementation instead of WASM.
* @param rounds - Optional: Number of PBKDF2 iterations to run (default: 210000).
*/
export function ledgerMaster (mnemonic: string, password?: string, rounds?: number): Uint8Array {
const seed = mnemonicToSeedSync(mnemonic, password, rounds);
const chainCode = hmacShaAsU8a(ED25519_CRYPTO, new Uint8Array([1, ...seed]), 256);
let priv;
+8 -2
View File
@@ -47,10 +47,16 @@ function deriveChecksumBits (entropyBuffer: Uint8Array): string {
).slice(0, (entropyBuffer.length * 8) / 32);
}
export function mnemonicToSeedSync (mnemonic: string, password?: string): Uint8Array {
/*
* @param mnemonic - The BIP-39 mnemonic phrase to derive the secret from.
* @param password - Optional: password to secure the seed (default: empty string).
* @param rounds - Optional: Number of PBKDF2 iterations to run (default: 210000).
*/
export function mnemonicToSeedSync (mnemonic: string, password?: string, rounds?: number): Uint8Array {
return pbkdf2Encode(
stringToU8a(normalize(mnemonic)),
stringToU8a(`mnemonic${normalize(password)}`)
stringToU8a(`mnemonic${normalize(password)}`),
rounds
).password;
}
@@ -21,8 +21,8 @@ describe('mnemonicToLegacySeed', (): void => {
it(`generates Wasm & Js equivalents for password=${password || 'undefined'}`, (): void => {
expect(
u8aEq(
mnemonicToLegacySeed(MNEMONIC, password, true),
mnemonicToLegacySeed(MNEMONIC, password, false)
mnemonicToLegacySeed(MNEMONIC, password, true, 32, 2048),
mnemonicToLegacySeed(MNEMONIC, password, false, 32, 2048)
)
).toEqual(true);
});
@@ -32,19 +32,19 @@ describe('mnemonicToLegacySeed', (): void => {
describe(`onlyJs=${(onlyJs && 'true') || 'false'}`, (): void => {
it('generates a valid 64bytes seed', (): void => {
expect(
u8aToHex(mnemonicToLegacySeed(MNEMONIC, undefined, onlyJs, 64))
u8aToHex(mnemonicToLegacySeed(MNEMONIC, undefined, onlyJs, 64, 2048))
).toEqual(SEED_64);
});
it('generates a valid 32bytes seed', (): void => {
expect(
u8aToHex(mnemonicToLegacySeed(MNEMONIC, undefined, onlyJs))
u8aToHex(mnemonicToLegacySeed(MNEMONIC, undefined, onlyJs, 32, 2048))
).toEqual(SEED_32);
});
it('fails with non-mnemonics', (): void => {
expect(
() => mnemonicToLegacySeed('foo bar baz', undefined, onlyJs)
() => mnemonicToLegacySeed('foo bar baz', undefined, onlyJs, 32, 2048)
).toThrow(/mnemonic specified/);
});
});
@@ -23,8 +23,14 @@ import { mnemonicValidate } from './validate.js';
* console.log(`Seed generated from mnemonic: ${mnemonicToLegacySeed(mnemonic)}`); => u8a
* }
* ```
*/
export function mnemonicToLegacySeed (mnemonic: string, password = '', onlyJs?: boolean, byteLength: 32 | 64 = 32): Uint8Array {
*
* @param mnemonic - The BIP-39 mnemonic phrase to derive the secret from.
* @param password - Optional: password to secure the seed (default: empty string).
* @param onlyJs - Optional: If `true`, forces use of the JavaScript implementation instead of WASM.
* @param byteLength - Optional: Either 32 or 64. Default is 32
* @param rounds - Optional: Number of PBKDF2 iterations to run (default: 210000).
*/
export function mnemonicToLegacySeed (mnemonic: string, password = '', onlyJs?: boolean, byteLength: 32 | 64 = 32, rounds?: number): Uint8Array {
if (!mnemonicValidate(mnemonic)) {
throw new Error('Invalid bip39 mnemonic specified');
} else if (![32, 64].includes(byteLength)) {
@@ -34,6 +40,6 @@ export function mnemonicToLegacySeed (mnemonic: string, password = '', onlyJs?:
return byteLength === 32
? !hasBigInt || (!onlyJs && isReady())
? bip39ToSeed(mnemonic, password)
: mnemonicToSeedSync(mnemonic, password).subarray(0, 32)
: mnemonicToSeedSync(mnemonic, password);
: mnemonicToSeedSync(mnemonic, password, rounds).subarray(0, 32)
: mnemonicToSeedSync(mnemonic, password, rounds);
}
@@ -20,8 +20,8 @@ describe('mnemonicToMiniSecret', (): void => {
it(`generates Wasm & Js equivalents for password=${password || 'undefined'}`, (): void => {
expect(
u8aEq(
mnemonicToMiniSecret(MNEMONIC, password, undefined, true),
mnemonicToMiniSecret(MNEMONIC, password, undefined, false)
mnemonicToMiniSecret(MNEMONIC, password, undefined, true, 2048),
mnemonicToMiniSecret(MNEMONIC, password, undefined, false, 2048)
)
).toEqual(true);
});
@@ -31,10 +31,10 @@ describe('mnemonicToMiniSecret', (): void => {
const mnemonic = '엉덩이 능동적 숫자 팩시밀리 비난 서적 파출소 도움 독창적 인생 상류 먼지 답변 음반 수박 사업 노란색 공사 우체국 특급 도대체 금지 굉장히 고무신';
expect(
() => mnemonicToMiniSecret(mnemonic, 'testing')
() => mnemonicToMiniSecret(mnemonic, 'testing', undefined, false, 2048)
).toThrow();
expect(
u8aToHex(mnemonicToMiniSecret(mnemonic, 'testing', koreanWords))
u8aToHex(mnemonicToMiniSecret(mnemonic, 'testing', koreanWords, false, 2048))
).toEqual('0xefa278a62535581767a2f49cb542ed91b65fb911e1b05e7a09c702b257f10c13');
});
@@ -42,20 +42,20 @@ describe('mnemonicToMiniSecret', (): void => {
describe(`onlyJs=${(onlyJs && 'true') || 'false'}`, (): void => {
it('generates a valid seed', (): void => {
expect(
u8aToHex(mnemonicToMiniSecret(MNEMONIC, undefined, undefined, onlyJs))
u8aToHex(mnemonicToMiniSecret(MNEMONIC, undefined, undefined, onlyJs, 2048))
).toEqual(SEED);
});
it('fails with non-mnemonics', (): void => {
expect(
() => mnemonicToMiniSecret('foo bar baz', undefined, undefined, onlyJs)
() => mnemonicToMiniSecret('foo bar baz', undefined, undefined, onlyJs, 2048)
).toThrow(/mnemonic specified/);
});
tests.forEach(([mnemonic, , seed], index): void => {
it(`Created correct seed for ${index}`, (): void => {
expect(
u8aToHex(mnemonicToMiniSecret(mnemonic, 'Substrate', undefined, onlyJs))
u8aToHex(mnemonicToMiniSecret(mnemonic, 'Substrate', undefined, onlyJs, 2048))
).toEqual(
// mini returned here, only check first 32-bytes (64 hex + 2 prefix)
seed.substring(0, 66)
@@ -8,7 +8,14 @@ import { pbkdf2Encode } from '../pbkdf2/index.js';
import { mnemonicToEntropy } from './toEntropy.js';
import { mnemonicValidate } from './validate.js';
export function mnemonicToMiniSecret (mnemonic: string, password = '', wordlist?: string[], onlyJs?: boolean): Uint8Array {
/**
* @param mnemonic - The BIP-39 mnemonic phrase to derive the secret from.
* @param password - Optional: password to secure the seed (default: empty string).
* @param wordlist - Optional custom wordlist for mnemonic.
* @param onlyJs - Optional: If `true`, forces use of the JavaScript implementation instead of WASM.
* @param rounds - Optional: Number of PBKDF2 iterations to run (default: 210000 (when onlyJS = true) or 2048 (when onlyJS = false).
*/
export function mnemonicToMiniSecret (mnemonic: string, password = '', wordlist?: string[], onlyJs?: boolean, rounds?: number): Uint8Array {
if (!mnemonicValidate(mnemonic, wordlist, onlyJs)) {
throw new Error('Invalid bip39 mnemonic specified');
} else if (!wordlist && !onlyJs && isReady()) {
@@ -19,5 +26,5 @@ export function mnemonicToMiniSecret (mnemonic: string, password = '', wordlist?
const salt = stringToU8a(`mnemonic${password}`);
// return the first 32 bytes as the seed
return pbkdf2Encode(entropy, salt).password.slice(0, 32);
return pbkdf2Encode(entropy, salt, rounds).password.slice(0, 32);
}
@@ -49,6 +49,6 @@ describe('pbkdf2Encode', (): void => {
}
perfWasm('pbkdf2Encode', 8, (input, onlyJs) =>
pbkdf2Encode(input, input, undefined, onlyJs)
pbkdf2Encode(input, input, 2048, onlyJs)
);
});
+8 -1
View File
@@ -15,7 +15,14 @@ interface Result {
salt: Uint8Array;
}
export function pbkdf2Encode (passphrase?: string | Uint8Array, salt: Uint8Array = randomAsU8a(), rounds = 2048, onlyJs?: boolean): Result {
export function pbkdf2Encode (passphrase?: string | Uint8Array, salt: Uint8Array = randomAsU8a(), rounds = 210000, onlyJs?: boolean): Result {
// When using the JS implementation (pbkdf2Js), large iteration counts can
// cause excessive computation time or memory usage. In that case, we cap
// the number of rounds to 2048 to ensure reliable performance.
if (onlyJs && rounds > 2048) {
rounds = 2048;
}
const u8aPass = u8aToU8a(passphrase);
const u8aSalt = u8aToU8a(salt);