Last active
January 8, 2020 21:27
-
-
Save magician11/c027e2cadc2743a3e188682429e2e5a7 to your computer and use it in GitHub Desktop.
How to encrypt and decrypt a message with TweetNaCl.js
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 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)}`); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It is really important to use a unique nonce for each encryption. and decryption all catigory