The hash algorithm
- Plaintext corresponds to ciphertext (Abstract) Teacher Yang corresponds to YLS
- The avalanche effect small changes lead to great changes
- Ciphertext cannot be reversed
- Fixed-length key MD5 SHA1 SHA256
Add salt to salt
let password = '123456'
let salt = '@Key! @ # '
let lastPwd = md5(password + salt)
/ / save:Save salt and lastPwd together as a database/ / readSalt is passed into the query along with lastPwdCopy the code
Commonly used background encryption writing method
Egg encryption
//app/controller/user.js
const md5 = require('md5')
const BaseController = require('./base')
const HashSalt = ':Kaikeba@good! @ 123 ' / / add salt
class UserController extends BaseController {
async login() {
// this.success('token')
const { ctx, app } = this
const { email, passwd } = ctx.request.body
// Query database by adding salt
const user = await ctx.model.User.findOne({
email,
passwd: md5(passwd + HashSalt),
})
if(! user) {return this.error('Wrong username and password')}...// this.success({ token, email, nickname: user.nickname })}}module.exports = UserController
Copy the code
Encryption methods
password.js
const crypto = require('crypto')// Use the encrypted library
const hash = (type,str) = > crypto.createHash(type).update(str).digest('hex')
const md5 = str= > hash('md5',str)
const sha1 = str= > hash('sha1',str)
const encryptPassword = (salt,password) = > md5(salt + 'asdbe! @ # @ 432 ' + password)
const psw = '111111'
// console.log('md5',md5(psw))
// console.log('sha1',sha1(psw))
// console.log('encryptPssword',encryptPassword(psw))
module.exports = encryptPassword
Copy the code
The test code
sqlTest.js
(async() = > {const query = require('./db')
const encryptPassword = require('./password')
let sql = ` SELECT * FROM test.user `
const res = await query(sql)
const saltDb = async record => {
sql = ` update test.user set salt = ? , password = ? where username = ? `
// Note that the salt is dynamically generated each time and recorded for the next query
const salt = Math.random() * 999999 + ' ' + new Date().getTime()
console.log('salt:', salt)
console.log('username:', record.username)
await query(sql, [salt, encryptPassword(salt, record.password), record.username])
}
res.forEach(v= > saltDb(v))
console.log('end',res)
})()
Copy the code