Skip to content

Instantly share code, notes, and snippets.

@righ
Last active August 1, 2020 07:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save righ/cb208f60e50b50b53a1dae5b25551b9e to your computer and use it in GitHub Desktop.
Save righ/cb208f60e50b50b53a1dae5b25551b9e to your computer and use it in GitHub Desktop.
pbkdf2 password hasher like django
const { pbkdf2Sync } = require('crypto');
export const validate = (raw, password, len=32) => {
const [method, iterations, salt, hash] = password.split('$');
const digest = method.split("_")[1];
return pbkdf2Sync(raw, salt, parseInt(iterations, 10), len, digest).toString('base64') === hash;
};
export const make = (raw, iterations, digest="sha256", salt="", len=32) => {
if (salt === "") {
salt = Math.random().toString(32).substring(2);
}
const hash = pbkdf2Sync(raw, salt, iterations, len, digest).toString('base64');
return `pbkdf2_${digest}$${iterations}$${salt}$${hash}`;
}
// -- test --
const hashed = make("test_pass", 10000);
console.log(hashed);
console.log(validate("test_pass", hashed));
import { pbkdf2Sync } from "crypto";
export const validate = (raw: string, password: string, len: number=32) => {
const [method, iterations, salt, hash] = password.split('$');
const digest = method.split("_")[1];
return pbkdf2Sync(raw, salt, parseInt(iterations, 10), len, digest).toString('base64') === hash;
};
export const make = (raw: string, iterations=10000, digest="sha256", salt="", len=32) => {
if (salt === "") {
salt = Math.random().toString(32).substring(2);
}
const hash = pbkdf2Sync(raw, salt, iterations, len, digest).toString('base64');
return `pbkdf2_${digest}$${iterations}$${salt}$${hash}`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment