background

For security reasons, the user name and password in the config file in the code were required to be encrypted, so I found some information and recorded my implementation and summary

plan

  • Using the configuration center, dynamically obtained through the interface
  • Use command line arguments
  • Write an encryption and decryption method, Mr. Ciphertext, config file to store ciphertext and key

The first option is easy to understand, but requires a remote configuration center. The second option is to put the user name and password in the code when you start the project, using process.argv. Because there is no remote configuration center, the first option is abandoned. I think the third scheme is more suitable for my situation, take a look at the code

// nodejs built-in encryption module const crypto = require("crypto") // config file secret_key and 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") }, // Decrypt dencrypt(encrypt) {let decipher = crypto.createDecipheriv(" AES192 ", key, iv) decipher.update(encrypt, "hex", "utf8") return decipher.final("utf8") }, }Copy the code

The config file

// use aes192 const config = {SECRET_KEY: 'testtesttesttesttesttesttest ', iv: 'testtesttesttest' } module.exports = config;Copy the code

The calling code

// encrypt.js
const { encrypt } = require("./util/md5")

console.log(encrypt("your username"))

console.log(encrypt("your password")) 

Copy the code

Using node encrypt.js, place the result in a config file.

Take connecting to mysql database as an example, how to use it in business code

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 = sequelizeCopy the code

The above is the implementation process of the third scheme

data

  • AES128, AES192, AES256 Encryption and decryption algorithm tool class
  • Crypto encryption