当前位置:网站首页>【Node实现数据加密】
【Node实现数据加密】
2022-07-30 19:21:00 【꒰ঌsnail໒꒱】
一、Node实现数据加密
1、加密的分类
(1)对称加密:也称为单密钥加密。同一个密钥进行加密和解密。
(2)非对称加密:有两把钥匙(公钥和私钥)
(3)摘要算法:把任意长度的输入,根据算法生成一串固定长度的伪随机数(没有密钥,加密过程是不可逆的)
2、MD5(摘要算法)在Node的使用方法
(1)安装crypto模块
npm install crypto
(2)使用crypto.createHash(‘md5’)32字节/(‘sha256’)64字节创建加密对象
(3)使用加密对象的update(明文)进行加密,然后调用digest(‘hex’)返回定长的十六进制字符串
3、示例
- 对用户的注册密码进行加密后存入数据库
(1)首先安装模块
npm install mysql2
npm install sequelize
(2)其次创建数据库连接的配置对象seqconfig.js文件。
//1、导入sequelize模块,引入框架
const Sequelize = require('sequelize')
//2、配置数据库连接对象
const mysqlDemo = new Sequelize('xy','root','123456',{
host:'localhost',
port:3306,
dialect:'mysql',//数据库方言,类型
pool:{
//数据库连接池
max:10,
min:3,
idle:100000
}
})
//3、导出数据库连接的配置对象
module.exports = mysqlDemo
(3)model的admin.js的模块,使用sequelize建立模型(类),该模型实现与数据表的orm映射.
const Sequelize = require('sequelize')
const orm =require('../seqconfig')
const AdminModel =orm.define('admin',{
Id:{
type:Sequelize.INTEGER,
primaryKey:true,//主键
autoIncrement:true,//自增
field:'id'
},
userName:{
type:Sequelize.STRING,
allowNull:false,
field:'username'
},
userPwd:{
type:Sequelize.STRING,
field:'userpwd'
}
},{
freezeTableName:true,
timestamps:false
})
module.exports = AdminModel;
(4)使用第三步创建的模型进行crud操作
const express = require('express')
const crypto = require('crypto')
const AdminModel = require('../config/model/admin')
const router = express.Router()
//http://localhost:3000/md5/register
router.post('/register',(req, res) => {
let name =req.body.username
let pwd = req.body.userpwd
//对密码进行加密
//生成加密对象
let hash = crypto.createHash('md5')
//使用加密对象进行加密并生成十六进制字符串
let newPwd = hash.update(pwd).digest('hex')
//将用户名和加密的密码保存到数据库中
AdminModel.create({
userName:name,
userPwd:newPwd
}).then((result)=>{
res.json({
code:1001,
msg:'保存成功'
})
}).catch((err)=>{
console.log(err)
res.json({
code:1002,
msg:'保存失败'
})
})
})
//http://localhost:3000/md5/login
router.post('/login',(req, res) => {
let name = req.body.username
let pwd =req.body.userpwd
//对密码进行加密
//生成加密对象
let hash = crypto.createHash('md5')
//使用加密对象进行加密并生成十六进制字符串
let newPwd = hash.update(pwd).digest('hex')
AdminModel.findOne({
where:{
userNmae:name
}
}).then((admin)=>{
if(admin.userPwd === newPwd){
res.json({
code:1001,
msg:'验证成功'
})
}else{
res.json({
code:1002,
msg:'密码错误,验证失败'
})
}
})
})
module.exports =router;
(5)别忘了最后要配置app.js文件
var md5Router = require('./routes/md5')
app.use('/md5',md5Router)
验证:
第四步的部分代码:将用户的注册密码进行加密后存入数据库
//http://localhost:3000/md5/register
router.post('/register',(req, res) => {
let name =req.body.username
let pwd = req.body.userpwd
//对密码进行加密
//生成加密对象
let hash = crypto.createHash('md5')
//使用加密对象进行加密并生成十六进制字符串
let newPwd = hash.update(pwd).digest('hex')
//将用户名和加密的密码保存到数据库中
AdminModel.create({
userName:name,
userPwd:newPwd
}).then((result)=>{
res.json({
code:1001,
msg:'保存成功'
})
}).catch((err)=>{
console.log(err)
res.json({
code:1002,
msg:'保存失败'
})
})
})
可以看到在postman测试成功:我们再来看看数据库,可以看到用户的密码加密信息保存到了数据库中:
第四步骤的部分代码,验证用户是否可以登录:
//http://localhost:3000/md5/login
router.post('/login',(req, res) => {
let name = req.body.username
let pwd =req.body.userpwd
//对密码进行加密
//生成加密对象
let hash = crypto.createHash('md5')
//使用加密对象进行加密并生成十六进制字符串
let newPwd = hash.update(pwd).digest('hex')
AdminModel.findOne({
where:{
userName:name
}
}).then((admin)=>{
if(admin.userPwd === newPwd){
res.json({
code:1001,
msg:'验证成功'
})
}else{
res.json({
code:1002,
msg:'密码错误,验证失败'
})
}
})
})
可以看到在postman测试成功:
(6)前后端分离,所以我们要写一个前端页面,进行前后端交互。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style> div{
width: 500px; margin: 100px auto; } </style>
<body>
<div>
<!-- <form action="" method="post"> -->
<label>
用户名:<input type="text" id="userName" name="username">
</label>
<br><br>
<label>
密 码:<input type="password" id="userPwd" name="userpwd">
</label>
<br><br>
<button type="button" id="btn_reset">重置</button>
<button type="button" id="btn_submit">提交</button>
<!-- </form> -->
<br><br>
<span id="msg"></span>
</div>
<script src="../js/jquery-3.4.1.js"></script>
<script> $(function(){
//jQuery入口函数 //1、给登录按钮绑定click事件 $('#btn_submit').click(function(){
//2、获取用户输入的密码和用户名 let name=$('#userName').val() let pwd = $('#userPwd').val() //3.调用ajax函数向服务器发送异步的请求 $.post('http://localhost:3000/md5/login',{
username:name,userpwd:pwd},function(result){
$('#msg').html(result.msg) },'json') }) }) </script>
</body>
</html>
输入用户张三和密码123456后,显示验证成功,也就表明了登录成功:
边栏推荐
- C# wpf borderless window add shadow effect
- requet.getHeader("token") is null
- 跨域问题的解决方法
- LeetCode 0952.按公因数计算最大组件大小:建图 / 并查集
- Tensorflow2.0 confusion matrix does not match printing accuracy
- NXP IMX8QXP更换DDR型号操作流程
- SimpleOSS第三方库libcurl与引擎libcurl错误解决方法
- SimpleOSS third-party library libcurl and engine libcurl error solution
- 跨进程启动后台服务
- The 17th "Revitalization Cup" National Youth Vocational Skills Competition - Computer Programmers (Cloud Computing Platform and Operation and Maintenance) Participation Review and Summary
猜你喜欢
VBA 连接Access数据库和Excle
【Swords Offer】Swords Offer 17. Print n digits from 1 to the largest
谷歌AlphaFold近日宣称预测出地球上几乎所有蛋白质结构
vxe-table实现复选框鼠标拖动选中
Scrapy framework is introduced
【每日一道LeetCode】——191. 位1的个数
[TypeScript]编译配置
Node encapsulates a console progress bar plugin
Talking about Contrastive Learning (Contrastive Learning) the first bullet
NXP IMX8QXP replacement DDR model operation process
随机推荐
阿里云武林头条活动分享
LeetCode 0952. Calculate Maximum Component Size by Common Factor: Mapping / Union Search
2种手绘风格效果比较,你更喜欢哪一种呢?
Mysql execution principle analysis
【flink】报错整理 Could not instantiate the executor. Make sure a planner module is on the classpath
Vulkan开启特征(feature)的正确姿势
Chapter 4 Controlling the Execution Flow
Golang logging library zerolog use record
基于inquirer封装一个控制台文件选择器
技术很牛逼,还需要“向上管理”吗?
NC | Tao Liang Group of West Lake University - TMPRSS2 "assists" virus infection and mediates the host invasion of Clostridium sothrix hemorrhagic toxin...
生物医学论文有何价值 论文中译英怎样翻译效果好
架构师如何成长
实体中增加操作方法
常见链表题及其 Go 实现
Listen to the boot broadcast
LeetCode每日一题(1717. Maximum Score From Removing Substrings)
Zabbix 5.0 监控教程(一)
[Prometheus] An optimization record of the Prometheus federation [continued]
MindSpore:【语音识别】DFCNN网络训练loss不收敛