How to encrypt and store user passwords in the express framework of nodejs (md5 encrypts and stores user information)

foreword

At the beginning of the registration function, you can see the data in the database as follows:
the password is displayed directly
insert image description here
, but in actual operation, we need to encrypt the user's password and then store it in the database to ensure data security.
This section will introduce how to Use md5 to encrypt and store user passwords

Import the built-in module crypto

Create a new utils folder, and create a new file md5.js in it to write the encryption method.
Here we need to use a built-in module crypto, just import it directly

const crypto = require('crypto')

use crypto

const crypto = require('crypto')
var d = crypto.createHash('md5').update('123').digest('hex')

Let's talk about the meaning of the parameters:

  1. Use the crypto.createHash method, the content in the brackets behind represents the encryption method used, here is md5
  2. The following .updata represents what content is encrypted
  3. .digest is the algorithm selected for encryption, here use hex

The above code is to encrypt 123, we print it out to see the result: the
insert image description here
above ciphertext is the result of encrypting 123, md5 encryption has a characteristic: the ciphertext result after encrypting the same value is the same, so that It will lead to brute force cracking (take the ciphertext in the library to find the corresponding plaintext). There are the following solutions to this problem;
4. Add a string prefix before the encrypted value, such as:
If you don’t know the previous What is the string, it is difficult to crack the following password

const crypto = require('crypto')
var d = crypto.createHash('md5').update('by' + '123').digest('hex')
  1. Double-layer encryption is to encrypt the ciphertext again after obtaining the ciphertext for the first time

export method

The use of encryption is explained above, and the method is directly exported below for easy use:

const crypto = require('crypto')
module.exports = str => {
    
    
  return crypto.createHash('md5')
    .update('by' + str)
    .digest('hex')
}

use encryption method

The above is exported, and we can use it directly.
Here I use it directly in userModel.js, first import the method, and then use the set method in password to call the md5 encryption method we encapsulated:

password: {
    
    
    type: String,
    required: true,
    set: value => md5(value),
    select:false
  },

So you're done~~ Conduct a test, send a registration request, and view the database.
The user's password in the database has been encrypted:
insert image description here

Guess you like

Origin blog.csdn.net/weixin_45745641/article/details/127469593
Recommended