Skip to content

Instantly share code, notes, and snippets.

@mmyoji
Last active June 17, 2022 06:40
Show Gist options
  • Save mmyoji/77b552bb122c22848e255bfe3933af2e to your computer and use it in GitHub Desktop.
Save mmyoji/77b552bb122c22848e255bfe3933af2e to your computer and use it in GitHub Desktop.
Generate encrypted password and verify it with Node.js standard library
# see: https://nodejs.org/api/crypto.html#cryptoscryptpassword-salt-keylen-options-callback
import { scrypt as _scrypt } from "node:crypto";
import { promisify } from "node:util";
const scrypt = promisify(_scrypt);
// e.g.) crypto.ramdomUUID().replace(/-/g, "")
const SALT = "random chars at least 16 bytes";
export async function encryptPassword(password: string): Promise<string> {
const derivedKey = await scrypt(password, SALT, 64);
// @ts-ignore
return derivedKey.toString("hex");
}
export async function verifyPassword(
password: string,
encryptedPassword: string,
): Promise<boolean> {
const derivedKey = await encryptPassword(password);
return derivedKey === encryptedPassword;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment