Skip to content

Commit b07c64b

Browse files
committed
Use native browser hashing for pwnedPasswords check
1 parent bf25815 commit b07c64b

2 files changed

Lines changed: 11 additions & 3 deletions

File tree

src/lib/api/pwnedPasswords.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,12 @@
1-
import SHA1 from 'crypto-js/sha1';
1+
import { HashString } from "$lib/utils/crypto";
22

33
export async function checkPwnedCount(password: string): Promise<number> {
44
if (!password) {
55
throw new Error('Password cannot be empty');
66
}
77

8-
const hash = SHA1(password).toString();
8+
const hash = await HashString(password, 'SHA-1');
99
const hashPrefix = hash.substring(0, 5);
10-
const hashSuffix = hash.substring(5).toUpperCase();
1110

1211
let raw: string;
1312
try {
@@ -18,6 +17,7 @@ export async function checkPwnedCount(password: string): Promise<number> {
1817
throw new Error('Error while fetching pwned passwords range');
1918
}
2019

20+
const hashSuffix = hash.substring(5).toUpperCase();
2121
const match = raw.split('\n').find((line) => line.startsWith(hashSuffix));
2222

2323
if (match) {

src/lib/utils/crypto.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
const EncodeString = (input: string) => new TextEncoder().encode(input);
2+
const ArrayBufferToHex = (buffer: ArrayBuffer) => Array.from(new Uint8Array(buffer)).map((b) => b.toString(16).padStart(2, '0')).join('');
3+
4+
export async function HashString(input: string, hashtype: 'SHA-1' | 'SHA-256'): Promise<string> {
5+
const data = EncodeString(input);
6+
const hashBuffer = await crypto.subtle.digest(hashtype, data);
7+
return ArrayBufferToHex(hashBuffer);
8+
}

0 commit comments

Comments
 (0)