Keep your data secret using tweetnacl

Cryptography is a method of protecting information and communications through the use of codes so that only those for whom the information is intended can read and process it.

There are different ways to encrypt and decrypt data in javascript. Here I have given a short example for tweetnacl one of the packages to encrypt and decrypt data.


NaCl (pronounced “salt”) is an abbreviation for “Networking and Cryptography library”, a public domain “…high-speed software library for network communication, encryption, decryption, signatures, etc.

NaCl was created by the mathematician and programmer Daniel J. Bernstein.


To install tweetnacl via a package manager:


$ yarn add tweetnacl


$ npm install tweetnacl

We also need to install tweet-nacl-util for encode and decode in utf-8 and base64

$ npm install tweetnacl-util

Is tweetNacl secure?

TweetNaCL’s code has been written by experts, has been carefully reviewed, and is something you can trust. The only catch is that it is very slow.


The example for encryption is as follows:

Note that keyPairObj, nonce and box changes on every hit.


Using the same encryptedData, secretKeyString, publicKeyString, nonceString from encrypted data. We can decrypt the data.

Alternatives JS libraries

Libsodium (a NaCl fork)


GitRepo for demo



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store