Skip to content

Instantly share code, notes, and snippets.

@authmane512
Created October 27, 2018 13:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save authmane512/3b14bbc2335bb8ffc30004b29d8b4de5 to your computer and use it in GitHub Desktop.
Save authmane512/3b14bbc2335bb8ffc30004b29d8b4de5 to your computer and use it in GitHub Desktop.
const nacl = require('tweetnacl');
const util = require('tweetnacl-util');
const scrypt = require('scryptsy');
const fs = require('fs');
let password = "Node.js is cool";
let secret_msg = util.decodeUTF8("NPM is amazing!"); // function should be named "encodeUTF8", they reversed names!
// Generate the key:
let salt = nacl.randomBytes(16);
console.log("salt:", salt); // To decrypt the data later, you have to save this salt somewhere.
let N = 16384; // number of iterations
let r = 8; // Memory factor
let p = 1; // Parallelization factor
let key = scrypt(password, salt, N, r, p, nacl.secretbox.keyLength);
console.log(key);
// Encrypt the data:
let nonce = nacl.randomBytes(nacl.secretbox.nonceLength);
console.log("nonce:", nonce); // To decrypt the data later, you have to save this salt somewhere.
let encrypted = nacl.secretbox(secret_msg, nonce, key);
// Encode in Base64:
encrypted = util.encodeBase64(encrypted);
// Store encrypted data:
fs.writeFile('file.txt', encrypted, 'ascii', function(err) { // no need of utf8 with Base64
if (err) {
console.log(err);
} else {
console.log("File saved!");
}
});
@authmane512
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment