@zaneray/zcrypt
v1.0.1
Published
A simple library for generating salted password hashes and validating plain text passwords against them.
Maintainers
Keywords
Readme
ZCrypt
A simple library for generating salted password hashes and validating plain text passwords against them.
Overview
ZCrypt uses Node.js's built-in crypto module to perform password hashing using the pbkdf2Sync algorithm with a SHA512 digest. It requires a salt to be provided during initialization, ensuring that the same password does not result in the same hash across different applications.
Installation
Install the package from npm and add it to your package.json:
npm install @zaneray/zcryptUsage
Here's how to use ZCrypt to hash and validate passwords.
1. Initialize ZCrypt
First, you need to create an instance of ZCrypt with a salt. The salt should be a securely generated, unique string for your application.
import ZCrypt from '@zaneray/zcrypt';
const salt = 'your-super-secret-and-unique-salt';
const zcrypt = new ZCrypt(salt);2. Create a Password Hash
Use the createHash method to generate a hash for a user's password. You should store this hash in your database.
const password = 'mySecurePassword123';
const hashedPassword = zcrypt.createHash(password);
console.log(hashedPassword);
// Outputs a 128-character hex string3. Validate a Password
When a user tries to log in, use the validatePassword method to compare the plain text password they provide with the stored hash.
const loginPassword = 'mySecurePassword123';
const storedHash = 'the-hash-you-saved-in-the-database'; // The output from createHash
const isPasswordCorrect = zcrypt.validatePassword(loginPassword, storedHash);
if (isPasswordCorrect) {
console.log('Password is correct!');
} else {
console.log('Incorrect password.');
}Command-Line Scripts
The package includes two scripts that can be run from the command line for convenience.
generate-pw-hash
This script generates a hashed password using plain text password set in ZCRYPT_PW and the salt set in ZCRYPT_PASSWORD_SALT. It requires two environment variables to be set in you .env file you create from the .env-sample file.
ZCRYPT_PASSWORD_SALT: The salt to use for hashing.ZCRYPT_PW: The plain text password to hash.
You can run the script like this:
npm run generate-pw-hashtest
This script runs a test to ensure that the hashing and validation are working correctly. It uses the same environment variables set in your .env file as generate-pw-hash to create a hash and then validates it.
npm testAPI
new ZCrypt(salt)
salt(String): The salt to be used for hashing.
Creates a new ZCrypt instance.
createHash(password)
password(String): The plain text password to hash.
Returns a hex-encoded string of the hashed password.
validatePassword(password, hash)
password(String): The plain text password to validate.hash(String): The hash to compare against.
Returns true if the password matches the hash, and false otherwise.
