In ancient times, not only the world’s talent, but also the indomitable ambition – Su Shi
Writing in the front
When writing the server, we often encounter the business logic of storing passwords. If our database stores plaintext passwords, it will be very insecure. Bcrypt module helps you solve this problem.
Bcrypt module overview
Bcrypt is a cross-platform file encryption tool. Files encrypted by it can be transferred on all supported operating systems and processors. Its password must be 8 to 56 characters long and will be internally converted to a 448-bit key.
The encryption used is single-threaded, that is, it can be encrypted but not decrypted, and random strings can be generated during encryption to make the password more difficult
Using the step
// Import bcrypt module
const bcrypt = require('bcrypt');
// generate random string gen => generate generate salt code
let salt = await bcrypt.genSalt(10);
// Encrypts the password with a random string
let pass = await bcrypt.hash('Plaintext password', salt);
Copy the code
The password pair uses the following code
// Password comparison
let isEqual = await bcrypt.compare('Plaintext password'.'Encrypted password');
Copy the code
Installation steps
Before installing bcrypt with the NPM command, we need to install its dependencies:
-
Python 2.X
-
node-gyp
The command
npm install -g node-gyp Copy the code
-
windows-build-tools
The command
npm install --global --production windows-build-tools Copy the code
-
Install the bcrypt third-party module
The command
npm i bcrypt Copy the code
Complete sample code
/ / import bcrypt
const bcrypt = require('bcrypt')
async function run() {
/* Produces a random string using the bcrypt.gensalt () method which takes a number as an argument * The larger the number, the higher the complexity of the generated random string * the smaller the number, the lower the complexity of the generated random string default is 10 Returns a randomly generated string */
const salt = await bcrypt.genSalt(10);
/* Use the bcrypt.hash() method to encrypt the password. Plain text * 2. Random string returns the encrypted password */
const result = await bcrypt.hash('123456', salt)
console.log(salt);
console.log(result);
/* Use the bcrypt.pare () method to check the password parameters: * plaintext password * encrypted password returns a Boolean value */
let isEqual = await bcrypt.compare('123456', result);
console.log(isEqual); // true
}
run()
Copy the code