Skip to content

Instantly share code, notes, and snippets.

@magician11
Last active January 8, 2020 21:27
Show Gist options
  • Save magician11/c027e2cadc2743a3e188682429e2e5a7 to your computer and use it in GitHub Desktop.
Save magician11/c027e2cadc2743a3e188682429e2e5a7 to your computer and use it in GitHub Desktop.
How to encrypt and decrypt a message with TweetNaCl.js
const tweetnacl = require('tweetnacl'); // https://github.com/dchest/tweetnacl-js
tweetnacl.util = require('tweetnacl-util'); // https://github.com/dchest/tweetnacl-util-js
// utility function to display the Uint8Array
const asciiArmored = arr => tweetnacl.util.encodeBase64(arr);
// generate the key to encrypt a message
const secretKey = tweetnacl.randomBytes(32);
console.log(`secret key: ${asciiArmored(secretKey)}`);
// the nonce
const nonce = tweetnacl.randomBytes(24);
console.log(`nonce: ${asciiArmored(nonce)}`);
// the message to be encrypted
const message = 'some secret message with some secret credentials';
const decodedMessage = tweetnacl.util.decodeUTF8(message);
// perform the encryption
const encryptedMessage = tweetnacl.secretbox(decodedMessage, nonce, secretKey);
console.log(`encrypted message: ${asciiArmored(encryptedMessage)}`);
// decrypt the encrypted message
const originalMessage = tweetnacl.secretbox.open(
encryptedMessage,
nonce,
secretKey
);
console.log(`decrypted message: ${tweetnacl.util.encodeUTF8(originalMessage)}`);
@benamare164
Copy link

It is really important to use a unique nonce for each encryption. and decryption all catigory

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