Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save GuillermoPena/945b97278e689b779d94 to your computer and use it in GitHub Desktop.
Save GuillermoPena/945b97278e689b779d94 to your computer and use it in GitHub Desktop.
NodeJS - CRYPTO : Symmetric Cryptography of Files
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