代码地址:https://github.com/changeclass/Node_Blog.git
# Sql 注入
为了预防 sql 注入,我们需要使用 excape
。在导出 exec
处在导出一个 escape
(原生提供)。
module.exports = { | |
exec, | |
escape:mysql.escape | |
} |
接下来在 controller/user.js
中修改两个参数,并将 sql 语句中的单引号去掉。
username = escape(username) | |
password = escape(password) | |
const sql = `select username,realname from users where username=${username} and password=${password};` |
excape 会将整体作为一个字符串(也就是对特殊符号进行转义),从而避免 sql 注入。
# xss 攻击
在页面展示内容中掺杂 js 代码,以获取网页信息
安装 xss 工具
yarn add xss
使用工具
同样在
controller/blog.js
的顶部引入模块const xss = require('xss')
在需要引入的字段中引入
const title =xss(blogData.title)
const content = xss(blogData.content)
# 密码加密
nodejs 自带一个加密模块 crypto
,因此可以使用这个模块进行加密。
const crypto = require('crypto') | |
// 密匙 | |
const SECRET_KEY = 'sadjilk@#112321' | |
// MD5 加密 | |
function md5(content){ | |
let md5 = crypto.createHash('md5') | |
return md5.update(content).digest('hex') | |
} | |
// 加密函数 | |
function genPassword(password){ | |
const str = `password=${password}&key=${SECRET_KEY}` | |
return md5(str) | |
} |
MD5 加密是不可逆的加密,如果字符串相同,那么加密结果也是一样的。
例如:我们调用三次加密函数
genPassword('123') | |
genPassword('abc') | |
genPassword('123') |
至此,只需要在查询时查询加密字符串即可。
const login = (username, password) => { | |
username = escape(username) | |
// 加密密码 | |
password = genPassword(password) | |
password = escape(password) | |
const sql = `select username,realname from users where username=${username} and password=${password};` | |
return exec(sql).then(rows => { | |
return rows[0] || {} | |
}) | |
} |