> npm i simple_json_file_encryptor
Background: This tool is useful to you if your DB configs are in plain text as below: config.js
// This config should not be uploaded to any code repo
const mysqlDBConfig = {
host: '192.168.1.1',
user: 'root',
password: '1234567',
database: 'my_database',
}
This tool is what you need to make your sensitive data secrue
Now, let's use this tool to secur your sensitive data.
Create a json file named 'sensitive-data.json' and put all sensitive data into it. Put it into a secret folder (Sure, you can call it any name and put it anywhere you want)
sensitive-data.json:
{
"db": {
"user": "root",
"password": "1234567",
}
}
folder structure:
project-root/
|-src
|-secret
|- sensitive-data.json <---- DANGER to be exposed
|-config.js <---- OK to be exposed
|-package.json
|-
and your config.js will be like
import * as fs from 'fs';
const fileraw = fs.readSync('./secret/sensitive-data.json');
const sensitiveData = JSON.parse(fileraw);
const mysqlDBConfig = {
host: '192.168.1.1',
user: sensitiveData.db.user,
password: sensitiveData.db.password,
database: 'my_database',
}
Now, you are safe to upload the config file to code repo since all sensitive data were moved out.
But the sensitive data is still in plain text and NOT SAFE to be traced in code repo. Let's secure it with this new tool.
Open a termial under your project folder and run:
> npx simple_json_file_encryptor --path ./secret/sensitive-data.json --key MY_SECRET_KEY
(Above command will generate a new file named 'sensitive-data.json.crpt' in the same folder)
folder structure will be as below:
project-root/
|-src
|-secret
|- sensitive-data.json <--- DANGER to be exposed
|- sensitive-data.json.crpt <--- SAFE to be exposed
|-config.js
|-package.json
|-
If you open the file 'sensitive-data.json.crpt'
, you can only see an unreadable string:
3efqfdgtet19dnhaidu4nldnliwbeadf...
It is generated by hashing the json file content using key specified (in this case is 'MY_SECRET_KEY')
Back to your config file, and let's use fileEncryptor to restore sensitvie data from that unreadable hased string:
config.js:
import { fileEncryptor } from 'simple_json_file_encryptor';
const key = 'MY_SECRET_KEY'; // in real case, this value should be passed by ENV or ARGS
const sensitiveData = fileEncryptor.decryptFile(__dirname+'/secret/sensitive-data.json.crpt', key);
console.log('Successfully read sensitive data from encrypted file.'); // error will be thrown if failed
const mysqlDBConfig = {
host: '192.168.1.1',
user: sensitiveData.db.user,
password: sensitiveData.db.password,
database: 'my_database',
}
Your project should work as before with one extra output line saying: 'Successfully read sensitive data from encrypted file.' when first time config.js is imported.
Now, you can submit
config.js
andsensitive-data.json.crpt
to your code repo and ignore filesensitive-data.json
. Only the secret key needs to be kept out of public now.