From 43ac36180692a1bd7838389f135841a51404852e Mon Sep 17 00:00:00 2001 From: Arjun Porwal <65214523+ap211unitech@users.noreply.github.com> Date: Fri, 13 Jun 2025 18:46:25 +0530 Subject: [PATCH] Add input length validation in `scryptFromU8a` function (#1990) * fix: add input length validation in scryptFromU8a function * fix: improve input validation in scryptFromU8a function * fix: linting * fix: update default Scrypt parameters for improved security * revert: 9070615 * fix: remove dymanic calculation --- packages/util-crypto/src/scrypt/fromU8a.ts | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/packages/util-crypto/src/scrypt/fromU8a.ts b/packages/util-crypto/src/scrypt/fromU8a.ts index 5178249d3..bbe1550af 100644 --- a/packages/util-crypto/src/scrypt/fromU8a.ts +++ b/packages/util-crypto/src/scrypt/fromU8a.ts @@ -14,10 +14,19 @@ interface Result { } export function scryptFromU8a (data: Uint8Array): Result { + if (!(data instanceof Uint8Array)) { + throw new Error('Expected input to be a Uint8Array'); + } + + // Ensure the input is exactly 44 bytes: 32 for salt + 3 * 4 for N, p, r + if (data.length < 32 + 12) { + throw new Error(`Invalid input length: expected 44 bytes, found ${data.length}`); + } + const salt = data.subarray(0, 32); - const N = u8aToBn(data.subarray(32 + 0, 32 + 4), BN_LE_OPTS).toNumber(); - const p = u8aToBn(data.subarray(32 + 4, 32 + 8), BN_LE_OPTS).toNumber(); - const r = u8aToBn(data.subarray(32 + 8, 32 + 12), BN_LE_OPTS).toNumber(); + const N = u8aToBn(data.subarray(32, 36), BN_LE_OPTS).toNumber(); + const p = u8aToBn(data.subarray(36, 40), BN_LE_OPTS).toNumber(); + const r = u8aToBn(data.subarray(40, 44), BN_LE_OPTS).toNumber(); // FIXME At this moment we assume these to be fixed params, this is not a great idea // since we lose flexibility and updates for greater security. However we need some