Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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)}`);
@magician11

This comment has been minimized.

Copy link
Owner Author

@magician11 magician11 commented Apr 13, 2018

This method I'm using will mean that to crack the encrypted data would take 10 to the power of 38 Tianhe-2 Supercomputers running for the entirety of the existence of everything to exhaust half of the keyspace of the 256 bit key I'll be using. Or if we could theoretically buy enough computers, we would need to spend about 10 to the power of 44 times the Gross World Product. And yet it would still take more energy than is produced on Earth to do.

@magician11

This comment has been minimized.

Copy link
Owner Author

@magician11 magician11 commented Apr 14, 2018

It is really important to use a unique nonce for each encryption.

Why?
If you XOR two encrypted messages encrypted with the same key, you could use crib dragging to uncover the original messages.

What to use for a unique nonce?
A 24-byte random nonce won't have practical collisions, so you could use this as the nonce each time you encrypt a message with the same key.

Storing the nonce?
Of course you need the specific nonce you encrypted the message with to decrypt it, so... You can just store nonces along with the encrypted data, they don't have to be secret.

@benamare164

This comment has been minimized.

Copy link

@benamare164 benamare164 commented Jan 8, 2020

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