Skip to content

Instantly share code, notes, and snippets.

@thirdreplicator
Created June 13, 2018 02:49
Show Gist options
  • Save thirdreplicator/80acaf8173036797d081df657f506d8c to your computer and use it in GitHub Desktop.
Save thirdreplicator/80acaf8173036797d081df657f506d8c to your computer and use it in GitHub Desktop.
DIY file encryption
#!/opt/node/bin/node
// ~/bin/lib_crypt.js
const fs = require('fs')
const spawn = require('child_process').spawn
const SUCCESS = 0
function in_out_file(direction, base_file_name) {
const file_arr = [base_file_name + '.enc', base_file_name + '.txt']
return (direction == 'en') ? file_arr.reverse() : file_arr
}
function crypt_args(direction, base_file_name) {
let [in_file, out_file] = in_out_file(direction, base_file_name)
const base_opts = ['enc', '-aes-256-cbc', '-in', in_file, '-out', out_file]
const extra = (direction == 'en') ? ['-salt'] : ['-d']
return base_opts.concat(extra)
}
function crypt(direction, base_file_name) {
const command = spawn('/usr/bin/openssl', crypt_args(direction, base_file_name))
const [in_file, out_file] = in_out_file(direction, base_file_name)
command.stdin.pipe(process.stdin);
command.stdout.pipe(process.stdout);
command.stderr.pipe(process.stderr);
command.on('exit', function (code) {
if (code == SUCCESS) {
fs.unlinkSync(in_file)
spawn('/bin/chmod', ['600', out_file])
}
});
}
module.exports = crypt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment