This assignment will allow you to play around with the bcrypt
package by building a CLI application
In this assignment you will be expected to write a small authentication function. There is no need to build a server or link to a database; we will be saving our data to the file system.
For this assignment you will have to;
- Use bcrypt to create a hash for a password (
register.js
), and save that to a file - Compare a password with the hashed password (
login.js
)
-
Initialise
npm
withnpm init
-
Install the bcrypt npm package
-
Import
bcrypt
intoregister.js
-
Write a function which takes a string as an argument, and uses
bcrypt.hash()
to hash the result and return the resultHint: For now, use
10
as the number of salt roundsHint: This method returns a promise, so you might want to use
async / await
or use.then()
-
Run your function with the
userInput
variable, which you can populate from your terminal by including an additional argument, for example:node register.js kittens
-
Test your function by using
console.log()
to display the output
Play around with the salt rounds value. Use small and large numbers.
- How long does the program take to run?
- What would an ideal salt rounds number be?
We would like to store the hash we generated in the previous function into a file, so we can read it again
-
In the file
register.js
, import the node.js file system libraryHint:
import { promises as fs } from 'fs';
for the promise version of the library -
Use the
fs.writeFile()
method to write the hash to a file
-
Open the file
login.js
-
Import
bcrypt
and the node js file system library (we will use it to read the file) -
Write a function which takes a string as an argument
-
Use the
fs.readFile()
method to read the hash you stored in the file you created when you ranregister.js
-
Use
bcrypt.compare()
to compare theuserInput
variable with the hash from the file you just read -
bcrypt.compare()
returns eithertrue
orfalse
- If
true
, display a message to the user stating that the passwords match - If
false
, display a message to the user stating that the passwords do not match
- If
-
Test your code by running
node login.js {password}
- where{password}
is the password you wish to test against the hash