node.js密码加密实践

crypto

crypto 模块提供了加密的功能,包括对 OpenSSL 的哈希、HMAC、加密、解密、签名、以及验证功能的一整套封装


const crypto = require('crypto');   // 使用require('crypto')来访问该模块
const secret = 'abcdefg';
const hash = crypto.createHamc('sha256', secret).update('I love cupcakes').digest('hex');
console.log(hash);

想要了解更多关于crypto模块的知识可以去看相关的知识,这里就不多说了
链接:http://nodejs.cn/api/crypto.html

实践

1. 关键代码

注册登录要以相同的方式进行处理,这样子的密码才会一致

const crypto = require('crypto');   // 引入加密模块

let userPwd = req.body.userPwd,
    md5 = crypto.createHash("md5");     // md5加密
let newPwd = md5.update(userPwd).digest("hex");

2. 前置

引入模块、参数定义、数据库连接

require('./../util/util');
let express = require('express');
let router = express.Router();
let mongoose = require('mongoose');
let Users = require('../models/users');

const crypto = require('crypto');   // 引入加密模块

const SUCCESS = 2000;       // 请求成功
const NO_LOGIN = 4003;      // 未登录
const NO_POWER = 4001;      // 没有权限
const ERROR = 5000;         // 请求失败
const EXCEPTION = 4005;     // 异常
const WARN = 2001;          // 警告

mongoose.connect('mongodb://127.0.0.1:27017/teacher', {useNewUrlParser: true});

mongoose.connection.on('connected', function () {
    console.log('MongoDB connected success.');
});

mongoose.connection.on('error', function () {
    console.log('MongoDB connected fail.');
});

mongoose.connection.on('disconnected', function () {
    console.log('MongoDB connected disconnected.')
});

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

3. 注册

// 注册 
router.post('/register', function (req, res, next) {
    let phone = req.body.phone,
        userPwd = req.body.userPwd,
        md5 = crypto.createHash("md5");
    let newPwd = md5.update(userPwd).digest("hex");
    let param = {
        createDate: '',
        phone: phone,
        userPwd: newPwd
    }
    // 检验手机号码是否被注册过
    Users.findOne({phone: param.phone}, function (err, doc) {
        if (err) {
            res.json({
                code: ERROR,
                msg: err.message,
                result: ''

            })
        } else {
            if (doc) {  // 手机号码被注册过
                res.json({
                    code: WARN,
                    msg: '该手机号码已被注册过',
                    result: ''
                })
            } else {    // 手机号码没有被注册过
                let createDate = new Date().Format('yyyy-MM-dd hh:mm:ss');
                param.createDate = createDate;
                Users.insertMany([param], function(err2, doc2) {
                    if (err2) {
                        res.json({
                            code: ERROR,
                            msg: err.message,
                            result: ''
                        })
                    } else {
                        res.json({
                            code: SUCCESS,
                            msg: '注册成功',
                            result: doc2
                        })
                    }
                })
            }
        }
    })
});

4. 登录


// 登录
router.post('/login', function (req, res, next) {
    let phone = req.body.phone,
        userPwd = req.body.userPwd;
    let md5 = crypto.createHash("md5");
    let pwd = md5.update(userPwd).digest("hex");
    let param = {
        phone: phone,
        userPwd: pwd
    }
    Users.findOne(param, function(err, doc) {
        if (err) {
            res.json({
                code: ERROR,
                msg: err.message,
                result: ''
            })
        } else {
            if (doc) {
                    // 存储cookie
                res.cookie('userId', doc._id, {
                    path: '/',
                    maxAge: 1000 * 60 * 60
                });
                res.json ({
                    code: SUCCESS,
                    msg: '登录成功',
                    result: {
                        phone: doc.phone,
                        userId: doc._id
                    }
                })
            } else {
                res.json ({
                    code: WARN,
                    msg: '账号或密码错误',
                    result: ''
                })
            }
        }
    })
});

你可能感兴趣的:(node.js密码加密实践)