UNPKG

@rikishi/secure-env

Version:
62 lines (54 loc) 2.59 kB
'use strict'; var crypto = require('crypto'); var fs = require('fs'); var log = require('./utils/log'); /* Arguments that can be passed are * --secret <secretKey> | -s <secretKey> * --out <file-path> | -o <file-path> * --algo <algoName> | -a <algoName> * --decrypt | -d */ module.exports.decrypt = function (options) { try { var secret = options.secret || 'mySecret'; var inputFile = options.file || '.env.enc'; var decryptionAlgo = options.decryptionAlgo || 'aes256'; var ivLength = options.ivLength || 16; if (!fs.existsSync(inputFile)) throw "".concat(inputFile, " does not exist."); if (!secret || typeof secret !== 'string') throw 'No SecretKey provided.'; var fileBuffer = fs.readFileSync(inputFile); var iv = fileBuffer.slice(0, ivLength); var ciphertext = fileBuffer.slice(ivLength, fileBuffer.length); var key = crypto.createHash('sha256').update(String(secret)).digest(); var decipher = crypto.createDecipheriv(decryptionAlgo, key, iv); decipher.setAutoPadding(false); var decrypted = decipher.update(ciphertext, 'hex', 'utf8'); decrypted += decipher["final"]('utf8'); return decrypted; } catch (e) { log(e, 'error'); } }; module.exports.encrypt = function (options) { try { var secret = options.secret || 'mySecret'; var inputFile = options.inputFile || '.env'; var outputFilePath = options.outputFile || "".concat(inputFile, ".enc"); var encryptionAlgo = options.encryptionAlgo || 'aes256'; var ivLength = options.ivLength || 16; // presumably createCipheriv() should work for all the algo in ./openssl_list-cipher-algorithms.csv with the right key/iv length if (!fs.existsSync(inputFile)) throw "Error: ".concat(inputFile, " does not exist."); if (!secret || typeof secret !== 'string') throw 'No SecretKey provided.Use -s option to specify secret'; var key = crypto.createHash('sha256').update(String(secret)).digest(); // node v10.5.0+ should use crypto.scrypt(secret, salt, keylen[, options], callback) var iv = crypto.randomBytes(ivLength); var cipher = crypto.createCipheriv(encryptionAlgo, key, iv); var output = fs.createWriteStream(outputFilePath); output.write(iv); fs.createReadStream(inputFile).pipe(cipher).pipe(output); output.on('finish', function () { log("The Environment file \"".concat(inputFile, "\" has been encrypted to \"").concat(outputFilePath, "\"."), 'info'); log("Make sure to delete \"".concat(inputFile, "\" for production use."), 'warn'); }); } catch (e) { log(e, 'error'); } };