Last active
June 17, 2022 06:40
-
-
Save mmyoji/77b552bb122c22848e255bfe3933af2e to your computer and use it in GitHub Desktop.
Generate encrypted password and verify it with Node.js standard library
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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