Skip to content

Instantly share code, notes, and snippets.

@magician11
Last active January 8, 2020 21:27
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
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)}`);
@magician11
Copy link
Author

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
Copy link
Author

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
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