Last active
August 23, 2018 01:19
-
-
Save HR/34201b32f22ced8659b8abba7332c709 to your computer and use it in GitHub Desktop.
Node.js AES file encryption with authentication promise
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
/** | |
* AES file encryption with authentication (using Promises) | |
* (C) Habib Rehman 2016 | |
******************************/ | |
const encrypt = function (origpath, destpath, key) { | |
// decrypts any arbitrary data passed with the pass | |
return new Promise(function (resolve, reject) { | |
// readstream to read the (unencrypted) file | |
const origin = fs.createReadStream(origpath) | |
// writestream to write (encrypted) file | |
const dest = fs.createWriteStream(destpath) | |
// generate a cryptographically secure random iv | |
const iv = scrypto.randomBytes(defaults.ivLength) | |
// create the AES-256-GCM cipher with iv and derive encryption key | |
const cipher = scrypto.createCipheriv(defaults.algorithm, key, iv) | |
// Read file, apply tranformation (encryption) to stream and | |
// then write stream to filesystem | |
origin.pipe(cipher).pipe(dest) | |
// readstream error handler | |
origin.on('error', (err) => { | |
// reject on readstream error | |
reject(err) | |
}) | |
// cipher error handler | |
cipher.on('error', (err) => { | |
// reject on cipher error | |
reject(err) | |
}) | |
// writestream error handler | |
dest.on('error', (err) => { | |
// reject on writestream | |
reject(err) | |
}) | |
// writestream finish handler | |
dest.on('finish', () => { | |
// get the generated Message Authentication Code | |
const tag = cipher.getAuthTag() | |
// return all the credentials used for encryption | |
resolve({ | |
key, | |
iv, | |
tag | |
}) | |
}) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment