Skip to content

Commit

Permalink
simplify node crypto logic
Browse files Browse the repository at this point in the history
  • Loading branch information
DavidSint committed Oct 27, 2024
1 parent 04357bb commit d569268
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 36 deletions.
22 changes: 1 addition & 21 deletions lib/hibp.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,4 @@
export async function createSha1Hash(
password: string,
nodeProcess?: NodeJS.Process,
): Promise<string> {
let nodeProcessOrUndefined: NodeJS.Process | undefined;
try {
nodeProcessOrUndefined = nodeProcess || process;
} catch (e) {
nodeProcessOrUndefined = undefined;
}
const isNode =
nodeProcessOrUndefined !== undefined &&
nodeProcessOrUndefined.versions != null &&
nodeProcessOrUndefined.versions.node != null;
if (isNode) {
const { createHash } = require("crypto");
const hash = createHash("sha1");
hash.update(password);
return hash.digest("hex");
}

export async function createSha1Hash(password: string): Promise<string> {
const encodedData = new TextEncoder().encode(password);
const buffer = await crypto.subtle.digest("SHA-1", encodedData);
const hashArray = Array.from(new Uint8Array(buffer));
Expand Down
20 changes: 6 additions & 14 deletions lib/tests/hibp.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,23 +44,15 @@ describe("createSha1 Tests", () => {
writable: true,
});

const referenceError = (() => {
try {
// Attempting to access an undefined variable, which will throw a ReferenceError to use
// @ts-ignore
console.log(undefinedVariable);
} catch (error) {
return error as ReferenceError;
}
})();

await createSha1Hash(
"123934534f",
referenceError as unknown as NodeJS.Process,
);
await createSha1Hash("123934534f");

expect(globalThis.crypto.subtle.digest).toHaveBeenCalled();

globalThis.crypto = cryptoSafeBox;
});

test("node web crypto API hash", async () => {
const hash = await createSha1Hash("123934534f");
expect(hash).toBe('180ecb35aebc323070f67bb14a5eced920e6d242')
});
});
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "password-tester",
"version": "1.2.1",
"version": "1.2.2",
"description": "Test password/phrases to ensure strong entropy and no reuse from a password breach, based on the latest guidance.",
"files": [
"dist"
Expand Down

0 comments on commit d569268

Please sign in to comment.