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.

Introduction:

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.

Installation:

To install tweetnacl via a package manager:

yarn:

$ yarn add tweetnacl

npm

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

Encryption:

The example for encryption is as follows:

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

Decryption:

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

Alternatives JS libraries

Libsodium (a NaCl fork)

Crypto.js

GitRepo for demo