Skip to content

Commit

Permalink
chore: use webcrypto for pbkdf2
Browse files Browse the repository at this point in the history
  • Loading branch information
wemeetagain committed Jul 12, 2024
1 parent 20f0b33 commit 7455701
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions src/kdf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ export async function kdf(mod: IKdfModule, password: Uint8Array): Promise<Uint8A
}
}
async function doPbkdf2(params: IPbkdf2KdfModule["params"], password: Uint8Array): Promise<Uint8Array> {
if (globalThis?.crypto?.subtle) {
return await doPbkdf2WebCrypto(params, password);
}
return pbkdf2(
password,
hexToBytes(params.salt),
Expand All @@ -53,6 +56,40 @@ async function doPbkdf2(params: IPbkdf2KdfModule["params"], password: Uint8Array
);
}

async function doPbkdf2WebCrypto(params: IPbkdf2KdfModule["params"], password: Uint8Array): Promise<Uint8Array> {
const passwordKey = await crypto.subtle.importKey(
"raw",
password,
"PBKDF2",
false,
["deriveKey"],
);
const key = await crypto.subtle.deriveKey(
{
name: "PBKDF2",
salt: hexToBytes(params.salt),
iterations: params.c,
hash: pickHash(params.prf.slice(5)),
},
passwordKey,
{ name: "AES-GCM", length: params.dklen * 8 },
true,
["encrypt", "decrypt"]
);
return new Uint8Array(await crypto.subtle.exportKey("raw", key));
}

function pickHash(hash: string): string {
hash = hash.toLowerCase();
if (hash === "sha256") {
return "SHA-256";
} else if (hash === "sha512") {
return "SHA-512";
} else {
throw new Error("Invalid hash type");
}
}

async function doScrypt(params: IScryptKdfModule["params"], password: Uint8Array): Promise<Uint8Array> {
return scrypt(
password,
Expand Down

0 comments on commit 7455701

Please sign in to comment.