File size: 1,574 Bytes
489b6e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
const iterations = 210_000;

function encode(bytes: Uint8Array) {
  return Buffer.from(bytes).toString("base64url");
}

async function derive(password: string, salt: Uint8Array, rounds = iterations) {
  const saltBuffer = salt.buffer.slice(salt.byteOffset, salt.byteOffset + salt.byteLength) as ArrayBuffer;
  const key = await crypto.subtle.importKey(
    "raw",
    new TextEncoder().encode(password),
    "PBKDF2",
    false,
    ["deriveBits"],
  );
  return new Uint8Array(await crypto.subtle.deriveBits(
    { name: "PBKDF2", salt: saltBuffer, iterations: rounds, hash: "SHA-256" },
    key,
    256,
  ));
}

export function validPassword(value: unknown) {
  return typeof value === "string" && value.length >= 8 && value.length <= 128;
}

export async function hashPassword(password: string) {
  const salt = crypto.getRandomValues(new Uint8Array(16));
  return `pbkdf2_sha256$${iterations}$${encode(salt)}$${encode(await derive(password, salt))}`;
}

export async function verifyPassword(password: string, stored: string) {
  const [algorithm, roundsValue, saltValue, expected] = stored.split("$");
  const rounds = Number(roundsValue);
  if (algorithm !== "pbkdf2_sha256" || !saltValue || !expected || rounds < 100_000) return false;
  const actual = encode(await derive(password, Buffer.from(saltValue, "base64url"), rounds));
  if (actual.length !== expected.length) return false;
  let mismatch = 0;
  for (let index = 0; index < actual.length; index += 1) {
    mismatch |= actual.charCodeAt(index) ^ expected.charCodeAt(index);
  }
  return mismatch === 0;
}