Skip to content

Instantly share code, notes, and snippets.

@VottusCode
Created October 6, 2020 18:43
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 VottusCode/b9e98e0cf947df90dad6b634ae84233c to your computer and use it in GitHub Desktop.
Save VottusCode/b9e98e0cf947df90dad6b634ae84233c to your computer and use it in GitHub Desktop.
Port of AuthMe's SHA256 hashing to Node.js
import { createHash } from "crypto";
import { range } from "lodash";
export class Sha256 {
/** Range of characters for salt generation */
private chars: string[];
public static SALT_LENGTH = 16;
constructor() {
this.chars = this.initCharRange();
}
isValidPassword(password: string, hash: string) {
const parts = hash.split("$");
const newHash = this.hash(password, parts[2]);
return hash === newHash;
}
hash(password: string, salt = this.generateSalt()) {
const makeHash = (str: string) =>
createHash("sha256").update(str, "utf8").digest("hex");
return "$SHA$" + salt + "$" + makeHash(makeHash(password) + salt);
}
generateSalt() {
let salt = "";
for (let i = 0; i < Sha256.SALT_LENGTH; i++) {
salt += this.chars[Math.floor(Math.random() * this.chars.length)];
}
return salt;
}
private initCharRange() {
const numbers = range(0, 9).map((el) => el.toString());
const letters = range("a".charCodeAt(0), "f".charCodeAt(0) + 1).map((el) =>
String.fromCharCode(el)
);
return numbers.concat(letters);
}
}
import { Sha256 } from "./Sha256";
const pass = new Sha256();
// Making password
const password = "password to hash";
pass.hash(password); // $SHA$3d4b303ad6ee1a8a$11d3f0ba42faa6f1d88b8bda832c89be4374fa54d4804d430df5d355b8a2e254
// Validating password
const hash = "$SHA$0e3badf733812b2b$00ed570f29027065051e6d10355f3242f9a1ed9d3df0bef433ca017935539d19"; // hash for password vottus123
const toValidate = "vottus123"
pass.isValidPassword(toValidate, hash); // true
pass.isValidPassword("wrong password", hash) // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment