Last active
January 8, 2020 21:27
Star
You must be signed in to star a gist
How to encrypt and decrypt a message with TweetNaCl.js
This file contains 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 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)}`); |
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.
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
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.