Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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);
// 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) {
} else {
console.log("File saved!");

This comment has been minimized.

Copy link
Owner Author

authmane512 commented Oct 27, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.