当前位置:网站首页>[Node implements data encryption]
[Node implements data encryption]
2022-07-30 19:42:00 【꒰ঌsnail໒꒱】
一、Node实现数据加密
1、加密的分类
(1)对称加密:也称为单密钥加密.The same key is used for encryption and decryption.
(2)非对称加密:有两把钥匙(公钥和私钥)
(3)摘要算法:把任意长度的输入,Generates a series of fixed-length pseudo-random numbers according to the algorithm(没有密钥,The encryption process is irreversible)
2、MD5(摘要算法)在Node的使用方法
(1)安装crypto模块
npm install crypto
(2)使用crypto.createHash(‘md5’)32字节/(‘sha256’)64bytes to create encrypted objects
(3)使用加密对象的update(明文)进行加密,然后调用digest(‘hex’)Returns a fixed-length hexadecimal string
3、示例
- The user's registered password is encrypted and stored in the database
(1)首先安装模块
npm install mysql2
npm install sequelize
(2)Next, create a configuration object for the database connectionseqconfig.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、Export a configuration object for a database connection
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)Use the model created in step 3 to proceedcrud操作
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')
//Encrypt with an encryption object and generate a hex string
let newPwd = hash.update(pwd).digest('hex')
//Save the username and encrypted password to the database
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')
//Encrypt with an encryption object and generate a hex string
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)Don't forget to configure at the endapp.js文件
var md5Router = require('./routes/md5')
app.use('/md5',md5Router)
验证:
Part of the code for the fourth step:The user's registered password is encrypted and stored in the database
//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')
//Encrypt with an encryption object and generate a hex string
let newPwd = hash.update(pwd).digest('hex')
//Save the username and encrypted password to the database
AdminModel.create({
userName:name,
userPwd:newPwd
}).then((result)=>{
res.json({
code:1001,
msg:'保存成功'
})
}).catch((err)=>{
console.log(err)
res.json({
code:1002,
msg:'保存失败'
})
})
})
可以看到在postman测试成功:我们再来看看数据库,You can see that the user's password encryption information is saved in the database:
Part of the code for the fourth step,验证用户是否可以登录:
//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')
//Encrypt with an encryption object and generate a hex string
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)前后端分离,So we are going to write a front-end page,进行前后端交互.
<!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>
Enter the user Zhang Sanhe password123456后,显示验证成功,It also indicates that the login is successful:
边栏推荐
猜你喜欢
已删除
阿里面试这些微服务还不会?那还是别去了,基本等通知
Golang logging library zerolog use record
MySQL大总结
SimpleOSS第三方库libcurl与引擎libcurl错误解决方法
mysql慢查询优化
MySQL six-pulse sword, SQL customs clearance summary
Cesium加载离线地图和离线地形
Google's AlphaFold claims to have predicted almost every protein structure on Earth
ERROR 1045 (28000) Access denied for user 'root'@'localhost'Solution
随机推荐
MySQL复制表结构、表数据的方法
golang日志库zerolog使用记录
ResNet18-实现图像分类
Alibaba Cloud Martial Arts Headline Event Sharing
青蛙跳台阶(递归和非递归)-------小乐乐走台阶
部分分类网络性能对比
Mac安装PHP开发环境
After MySQL grouping, take the largest piece of data [optimal solution]
架构师如何成长
试写C语言三子棋
Tensorflow2.0 混淆矩阵与打印准确率不符
【hbuilder】运行不了部分项目 , 打开终端 无法输入指令
VBA runtime error '-2147217900 (80040e14): Automation error
Range.CopyFromRecordset 方法 (Excel)
Linux download and install mysql5.7 version tutorial the most complete and detailed explanation
MindSpore:【MindSpore1.1】Mindspore安装后验证出现cudaSetDevice failed错误
MySQL six-pulse sword, SQL customs clearance summary
Another company interview
MindSpore:Cifar10Dataset‘s num_workers=8, this value is not within the required range of [1, cpu_thr
The technology is very powerful, do you still need to "manage up"?