Created
May 28, 2014 10:12
-
-
Save GuillermoPena/945b97278e689b779d94 to your computer and use it in GitHub Desktop.
NodeJS - CRYPTO : Symmetric Cryptography of Files
This file contains 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
var crypto = require('crypto') | |
, fs = require('fs') | |
var sourceFile = __dirname + "/testFile.txt" | |
, targetFile = __dirname + "/testEncryptedFile.txt" | |
, key = "SecretKey" | |
, algorithm = 'aes192' // Another algorithms: 'des-ede3-cbc' | |
, cipher = crypto.createCipher(algorithm, key) | |
, decipher = crypto.createDecipher(algorithm, key) | |
, rs = fs.ReadStream(sourceFile) | |
, ws = fs.WriteStream(targetFile) | |
// Encrypting a File | |
var fileContent = '' | |
var cryptedFileContent | |
rs.on('data', function(data) { | |
fileContent += data | |
cryptedFileContent = cipher.update(data, 'utf8', 'hex') | |
ws.write(cryptedFileContent) | |
}) | |
rs.on('end', function() { | |
var finalStream = cipher.final('hex') | |
// After use final method you can not use cipher again | |
cryptedFileContent+= finalStream | |
ws.write(finalStream, function(){ | |
console.log("\nEncrypt a File: " + sourceFile) | |
console.log("Target File: " + targetFile + "\nContent: " + fileContent) | |
console.log("Encrypted File Content : " + cryptedFileContent) | |
var cryptedTargetFileContent = fs.readFileSync(targetFile) | |
console.log("Target File Content : " + cryptedTargetFileContent) | |
}) | |
}) | |
// NOTE: To decrypt use decipher object of similar way |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment