Skip to content

Instantly share code, notes, and snippets.

@ProjectMoon
Created July 20, 2011 20:12
Show Gist options
  • Save ProjectMoon/1095807 to your computer and use it in GitHub Desktop.
Save ProjectMoon/1095807 to your computer and use it in GitHub Desktop.
Is there a problem with encrypting/decrypting binary files, or am I doing it wrong?
//invoke with a filename to encrypt and decrypt a specific file.
var fs = require('fs'),
crypto = require('crypto');
var ALG = 'aes256';
var KEY = 'test';
var ENCODING = 'hex';
var FILE = process.argv[2] || 'file.txt';
console.log(FILE);
var stream = fs.createReadStream(FILE);
var cipher = crypto.createCipher(ALG, KEY);
var encryptedFile = fs.createWriteStream(FILE + '.enc');
stream.on('data', function(data) {
var encrypted = cipher.update(data, null, ENCODING);
encryptedFile.write(encrypted);
});
stream.on('end', function() {
var encrypted = cipher.final(ENCODING);
encryptedFile.write(encrypted);
encryptedFile.end();
console.log('done encrypting');
});
stream.on('close', function() {
decrypt();
});
function decrypt() {
var stream2 = fs.createReadStream(FILE + '.enc');
var decipher = crypto.createDecipher(ALG, KEY);
var plainFile = fs.createWriteStream(FILE + '.uenc');
stream2.on('error', function(err) {
console.log('error: ' + err);
});
stream2.on('data', function(data) {
var plain = decipher.update(data, ENCODING);
plainFile.write(plain);
});
stream2.on('end', function() {
var plain = decipher.final();
plainFile.write(plain);
plainFile.end();
console.log('done decrypting');
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment