Last active
August 1, 2020 07:20
-
-
Save righ/cb208f60e50b50b53a1dae5b25551b9e to your computer and use it in GitHub Desktop.
pbkdf2 password hasher like django
This file contains 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
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)); | |
This file contains 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
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