UNPKG

@tree-house/authentication

Version:
37 lines (36 loc) 1.68 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.dehashPassword = exports.hashPassword = exports.comparePassword = exports.generateRandomHash = exports.getHashedPassword = void 0; const crypto_1 = __importDefault(require("crypto")); const bcryptjs_1 = __importDefault(require("bcryptjs")); function getHashedPassword(password, saltCount) { return bcryptjs_1.default.hash(password, saltCount); } exports.getHashedPassword = getHashedPassword; function generateRandomHash(algorithm = 'sha256', secret = Math.random().toString(36).slice(-8)) { return crypto_1.default.createHmac(algorithm, secret).digest('hex'); } exports.generateRandomHash = generateRandomHash; function comparePassword(password, hashedPw) { return bcryptjs_1.default.compare(password, hashedPw); } exports.comparePassword = comparePassword; function hashPassword(password, { algorithm, key, iv }) { const ivBuffer = Buffer.from(iv); const encryptor = crypto_1.default.createCipheriv(algorithm, key, ivBuffer); encryptor.setEncoding('hex'); encryptor.write(password); encryptor.end(); return encryptor.read().toString(); } exports.hashPassword = hashPassword; function dehashPassword(password, { algorithm, key, iv }) { const ivBuffer = Buffer.from(iv); const decryptor = crypto_1.default.createDecipheriv(algorithm, key, ivBuffer); const decryptedText = decryptor.update(password, 'hex'); return `${decryptedText}${decryptor.final('utf-8')}`; } exports.dehashPassword = dehashPassword;