Created
October 27, 2018 13:33
-
-
Save authmane512/3b14bbc2335bb8ffc30004b29d8b4de5 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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!"); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For decryption:
https://gist.github.com/authmane512/9c74b0270a4b10a5ccc202136a6b000b