背景
因为处于安全考虑,要求对代码中的 config 文件中的用户名和密码进行加密,所以就找了些资料,将自己的实现和总结记录下
方案
- 利用配置中心,通过接口动态获取
- 使用命令行参数
- 编写一个加密解密方法,先生成密文,config 文件存储密文和密钥
第一种方案,很好理解,不过需要有远程的配置中心 第二种方案,就是将用户名密码的输入放在启动项目的时候,利用 process.argv 在代码中获取 因为没有远程的配置中心,放弃了第一种方案,第二种方案,每次都需要输入,觉得麻烦 第三种方案比较符合我的情况,看下代码
// nodejs 内置加密模块
const crypto = require("crypto")
// 配置文件获取 secret_key 和 iv
const { SECRET_KEY, IV } = require("../config")
const key = Buffer.from(SECRET_KEY, "utf8")
const iv = Buffer.from(IV, "utf8")
module.exports = {
// 加密
encrypt(str) {
let cipher = crypto.createCipheriv("aes192", key, iv)
cipher.update(str, "utf-8", "hex")
return cipher.final("hex")
},
// 解密
dencrypt(encrypt) {
let decipher = crypto.createDecipheriv("aes192", key, iv)
decipher.update(encrypt, "hex", "utf8")
return decipher.final("utf8")
},
}
config 文件
// 采用 aes192,key 要 24 位,iv 要 16 位,不然加密方法会报错
const config = {
SECRET_KEY: 'testtesttesttesttesttest',
IV: 'testtesttesttest'
}
module.exports = config;
调用代码
// encrypt.js
const { encrypt } = require("./util/md5")
console.log(encrypt("your username"))
console.log(encrypt("your password"))
使用 node encrypt.js ,将执行结果放置在 config 文件中。
以连接 mysql 数据库为例,看看在业务代码中如何使用
const Sequelize = require("sequelize")
const { db } = require("../config")
const { dencrypt } = require("../util")
const sequelize = new Sequelize(
db.database,
dencrypt(db.username),
dencrypt(db.password),
{
host: db.host,
dialect: "mysql"
}
)
module.exports = sequelize
以上就是第三种方案的实现流程
资料