Convert Figma logo to code with AI

dchest logotweetnacl-js

Port of TweetNaCl cryptographic library to JavaScript

1,763
294
1,763
7

Top Related Projects

5,058

A native implementation of TLS in Javascript and tools to write crypto-based and network-heavy webapps

Fast Elliptic Curve Cryptography in plain javascript

7,188

Stanford Javascript Crypto Library

Quick Overview

TweetNaCl.js is a port of TweetNaCl cryptographic library to JavaScript. It provides a compact and auditable implementation of various cryptographic primitives, including public-key cryptography, encryption, and digital signatures. The library is designed to be small, fast, and easy to use in both Node.js and browser environments.

Pros

  • Small footprint: The entire library is around 7KB minified and gzipped
  • Pure JavaScript implementation, making it easy to use in various environments
  • Auditable due to its small codebase and straightforward implementation
  • Provides a wide range of cryptographic functions in a single package

Cons

  • Limited to the specific algorithms implemented in TweetNaCl
  • May not be as performant as native implementations or WebCrypto API for some operations
  • Lacks some advanced features found in larger cryptographic libraries
  • Not actively maintained, with the last update being several years ago

Code Examples

  1. Generating a key pair:
const nacl = require('tweetnacl');

const keyPair = nacl.box.keyPair();
console.log('Public key:', Buffer.from(keyPair.publicKey).toString('hex'));
console.log('Secret key:', Buffer.from(keyPair.secretKey).toString('hex'));
  1. Encrypting and decrypting a message:
const nacl = require('tweetnacl');
const util = require('tweetnacl-util');

const message = 'Hello, TweetNaCl!';
const nonce = nacl.randomBytes(nacl.box.nonceLength);
const keyPair = nacl.box.keyPair();

const encrypted = nacl.box(
  util.decodeUTF8(message),
  nonce,
  keyPair.publicKey,
  keyPair.secretKey
);

const decrypted = nacl.box.open(
  encrypted,
  nonce,
  keyPair.publicKey,
  keyPair.secretKey
);

console.log('Decrypted message:', util.encodeUTF8(decrypted));
  1. Signing and verifying a message:
const nacl = require('tweetnacl');
const util = require('tweetnacl-util');

const message = 'Sign this message';
const keyPair = nacl.sign.keyPair();

const signature = nacl.sign(util.decodeUTF8(message), keyPair.secretKey);
const verified = nacl.sign.open(signature, keyPair.publicKey);

console.log('Verified message:', util.encodeUTF8(verified));

Getting Started

To use TweetNaCl.js in your project, first install it via npm:

npm install tweetnacl tweetnacl-util

Then, in your JavaScript file:

const nacl = require('tweetnacl');
const util = require('tweetnacl-util');

// Now you can use nacl functions
const keyPair = nacl.box.keyPair();
console.log('Public key:', Buffer.from(keyPair.publicKey).toString('hex'));

Note that tweetnacl-util is optional but provides helpful encoding/decoding functions for working with strings.

Competitor Comparisons

5,058

A native implementation of TLS in Javascript and tools to write crypto-based and network-heavy webapps

Pros of Forge

  • Broader range of cryptographic functions and utilities
  • More extensive documentation and examples
  • Active development and regular updates

Cons of Forge

  • Larger file size and potentially slower performance
  • More complex API, steeper learning curve
  • May require additional setup for certain features

Code Comparison

TweetNaCl.js:

const nacl = require('tweetnacl');
const message = new Uint8Array([1, 2, 3]);
const nonce = nacl.randomBytes(24);
const key = nacl.randomBytes(32);
const encrypted = nacl.secretbox(message, nonce, key);

Forge:

const forge = require('node-forge');
const message = 'Hello, World!';
const key = forge.random.getBytesSync(16);
const iv = forge.random.getBytesSync(16);
const cipher = forge.cipher.createCipher('AES-CBC', key);
cipher.start({iv: iv});
cipher.update(forge.util.createBuffer(message));
cipher.finish();
const encrypted = cipher.output;

TweetNaCl.js focuses on simplicity and ease of use, providing a streamlined API for common cryptographic operations. Forge offers a more comprehensive set of tools and greater flexibility, but with increased complexity. TweetNaCl.js is ideal for projects requiring basic, lightweight cryptography, while Forge is better suited for applications needing advanced cryptographic features and customization options.

Fast Elliptic Curve Cryptography in plain javascript

Pros of elliptic

  • Supports a wider range of elliptic curves, including popular ones like secp256k1
  • More flexible and customizable for specific cryptographic needs
  • Generally faster performance for elliptic curve operations

Cons of elliptic

  • Larger codebase and more complex API, potentially harder to use
  • May require more careful implementation to ensure security
  • Less focus on overall cryptographic protocol implementation

Code Comparison

elliptic:

const EC = require('elliptic').ec;
const ec = new EC('secp256k1');
const key = ec.genKeyPair();
const signature = key.sign(msgHash);
console.log(key.verify(msgHash, signature));

tweetnacl-js:

const nacl = require('tweetnacl');
const keyPair = nacl.sign.keyPair();
const signature = nacl.sign(message, keyPair.secretKey);
console.log(nacl.sign.detached.verify(message, signature, keyPair.publicKey));

Summary

elliptic offers more flexibility and support for various elliptic curves, making it suitable for specific cryptographic requirements. However, tweetnacl-js provides a simpler API and focuses on overall cryptographic protocols, which may be preferable for general-purpose use or when ease of implementation is a priority. The choice between the two depends on the specific needs of the project and the developer's familiarity with elliptic curve cryptography.

7,188

Stanford Javascript Crypto Library

Pros of SJCL

  • More comprehensive cryptographic library with a wider range of algorithms and functions
  • Better documentation and examples for developers
  • Supports a broader range of platforms and environments

Cons of SJCL

  • Larger file size and potentially slower performance
  • Less focus on modern, post-quantum cryptography
  • More complex API, which may be overwhelming for simple use cases

Code Comparison

SJCL encryption example:

var plaintext = "Hello, World!";
var password = "secret";
var ciphertext = sjcl.encrypt(password, plaintext);

TweetNaCl.js encryption example:

const message = new TextEncoder().encode("Hello, World!");
const nonce = nacl.randomBytes(nacl.secretbox.nonceLength);
const key = nacl.randomBytes(nacl.secretbox.keyLength);
const ciphertext = nacl.secretbox(message, nonce, key);

SJCL offers a higher-level API with built-in key derivation, while TweetNaCl.js provides a lower-level API requiring manual nonce and key generation. SJCL's approach is more user-friendly for basic use cases, but TweetNaCl.js offers more control over the encryption process.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

TweetNaCl.js

Port of TweetNaCl / NaCl to JavaScript for modern browsers and Node.js. Public domain.

Demo: https://dchest.github.io/tweetnacl-js/

Documentation

Overview

The primary goal of this project is to produce a translation of TweetNaCl to JavaScript which is as close as possible to the original C implementation, plus a thin layer of idiomatic high-level API on top of it.

There are two versions, you can use either of them:

  • nacl.js is the port of TweetNaCl with minimum differences from the original + high-level API.

  • nacl-fast.js is like nacl.js, but with some functions replaced with faster versions. (Used by default when importing NPM package.)

Audits

TweetNaCl.js has been audited by Cure53 in January-February 2017 (audit was sponsored by Deletype):

The overall outcome of this audit signals a particularly positive assessment for TweetNaCl-js, as the testing team was unable to find any security problems in the library.

Read full audit report

While the audit didn't find any bugs, there has been 1 bug discovered and fixed after the audit.

Security Considerations

It is important to note that TweetNaCl.js is a low-level library that doesn't provide complete security protocols. When designing protocols, you should carefully consider various properties of underlying primitives.

No secret key commitment

While XSalsa20-Poly1305, as used in nacl.secretbox and nacl.box, meets the standard notions of privacy and authenticity for a secret-key authenticated-encryption scheme using nonces, it is not key-committing, which means that it is possible to find a ciphertext which decrypts to valid plaintexts under two different keys. This may lead to vulnerabilities if encrypted messages are used in a context where key commitment is expected.

Signature malleability

While Ed25519 as originally defined and implemented in nacl.sign meets the standard notion of unforgeability for a public-key signature scheme under chosen-message attacks, it is malleable: given a signed message, it is possible, without knowing the secret key, to create a different signature for the same message that will verify under the same public key. This may lead to vulnerabilities if signatures are used in a context where malleability is not expected.

Hash length-extension attacks

The SHA-512 hash function, as implemented by nacl.hash, is not resistant to length-extension attacks.

Side-channel attacks

While TweetNaCl.js uses algorithmic constant-time operations, it is impossible to guarantee that they are physically constant time given JavaScript runtimes, JIT compilers, and other factors. It is also impossible to guarantee that secret data is physically removed from memory during cleanup due to copying garbage collectors and optimizing compilers.

Installation

You can install TweetNaCl.js via a package manager:

Yarn:

$ yarn add tweetnacl

NPM:

$ npm install tweetnacl

or download source code.

Examples

You can find usage examples in our wiki.

Usage

All API functions accept and return bytes as Uint8Arrays. If you need to encode or decode strings, use functions from https://github.com/dchest/tweetnacl-util-js or one of the more robust codec packages.

In Node.js v4 and later Buffer objects are backed by Uint8Arrays, so you can freely pass them to TweetNaCl.js functions as arguments. The returned objects are still Uint8Arrays, so if you need Buffers, you'll have to convert them manually; make sure to convert using copying: Buffer.from(array) (or new Buffer(array) in Node.js v4 or earlier), instead of sharing: Buffer.from(array.buffer) (or new Buffer(array.buffer) Node 4 or earlier), because some functions return subarrays of their buffers.

Public-key authenticated encryption (box)

Implements x25519-xsalsa20-poly1305.

nacl.box.keyPair()

Generates a new random key pair for box and returns it as an object with publicKey and secretKey members:

{
   publicKey: ...,  // Uint8Array with 32-byte public key
   secretKey: ...   // Uint8Array with 32-byte secret key
}

nacl.box.keyPair.fromSecretKey(secretKey)

Returns a key pair for box with public key corresponding to the given secret key.

nacl.box(message, nonce, theirPublicKey, mySecretKey)

Encrypts and authenticates message using peer's public key, our secret key, and the given nonce, which must be unique for each distinct message for a key pair.

Returns an encrypted and authenticated message, which is nacl.box.overheadLength longer than the original message.

nacl.box.open(box, nonce, theirPublicKey, mySecretKey)

Authenticates and decrypts the given box with peer's public key, our secret key, and the given nonce.

Returns the original message, or null if authentication fails.

nacl.box.before(theirPublicKey, mySecretKey)

Returns a precomputed shared key which can be used in nacl.box.after and nacl.box.open.after.

nacl.box.after(message, nonce, sharedKey)

Same as nacl.box, but uses a shared key precomputed with nacl.box.before.

nacl.box.open.after(box, nonce, sharedKey)

Same as nacl.box.open, but uses a shared key precomputed with nacl.box.before.

Constants

nacl.box.publicKeyLength = 32

Length of public key in bytes.

nacl.box.secretKeyLength = 32

Length of secret key in bytes.

nacl.box.sharedKeyLength = 32

Length of precomputed shared key in bytes.

nacl.box.nonceLength = 24

Length of nonce in bytes.

nacl.box.overheadLength = 16

Length of overhead added to box compared to original message.

Secret-key authenticated encryption (secretbox)

Implements xsalsa20-poly1305.

nacl.secretbox(message, nonce, key)

Encrypts and authenticates message using the key and the nonce. The nonce must be unique for each distinct message for this key.

Returns an encrypted and authenticated message, which is nacl.secretbox.overheadLength longer than the original message.

nacl.secretbox.open(box, nonce, key)

Authenticates and decrypts the given secret box using the key and the nonce.

Returns the original message, or null if authentication fails.

Constants

nacl.secretbox.keyLength = 32

Length of key in bytes.

nacl.secretbox.nonceLength = 24

Length of nonce in bytes.

nacl.secretbox.overheadLength = 16

Length of overhead added to secret box compared to original message.

Scalar multiplication

Implements x25519.

nacl.scalarMult(n, p)

Multiplies an integer n by a group element p and returns the resulting group element.

nacl.scalarMult.base(n)

Multiplies an integer n by a standard group element and returns the resulting group element.

Constants

nacl.scalarMult.scalarLength = 32

Length of scalar in bytes.

nacl.scalarMult.groupElementLength = 32

Length of group element in bytes.

Signatures

Implements ed25519.

nacl.sign.keyPair()

Generates new random key pair for signing and returns it as an object with publicKey and secretKey members:

{
   publicKey: ...,  // Uint8Array with 32-byte public key
   secretKey: ...   // Uint8Array with 64-byte secret key
}

nacl.sign.keyPair.fromSecretKey(secretKey)

Returns a signing key pair with public key corresponding to the given 64-byte secret key. The secret key must have been generated by nacl.sign.keyPair or nacl.sign.keyPair.fromSeed.

nacl.sign.keyPair.fromSeed(seed)

Returns a new signing key pair generated deterministically from a 32-byte seed. The seed must contain enough entropy to be secure. This method is not recommended for general use: instead, use nacl.sign.keyPair to generate a new key pair from a random seed.

nacl.sign(message, secretKey)

Signs the message using the secret key and returns a signed message.

nacl.sign.open(signedMessage, publicKey)

Verifies the signed message and returns the message without signature.

Returns null if verification failed.

nacl.sign.detached(message, secretKey)

Signs the message using the secret key and returns a signature.

nacl.sign.detached.verify(message, signature, publicKey)

Verifies the signature for the message and returns true if verification succeeded or false if it failed.

Constants

nacl.sign.publicKeyLength = 32

Length of signing public key in bytes.

nacl.sign.secretKeyLength = 64

Length of signing secret key in bytes.

nacl.sign.seedLength = 32

Length of seed for nacl.sign.keyPair.fromSeed in bytes.

nacl.sign.signatureLength = 64

Length of signature in bytes.

Hashing

Implements SHA-512.

nacl.hash(message)

Returns SHA-512 hash of the message.

Constants

nacl.hash.hashLength = 64

Length of hash in bytes.

Random bytes generation

nacl.randomBytes(length)

Returns a Uint8Array of the given length containing random bytes of cryptographic quality.

Implementation note

TweetNaCl.js uses the following methods to generate random bytes, depending on the platform it runs on:

  • window.crypto.getRandomValues (WebCrypto standard)
  • window.msCrypto.getRandomValues (Internet Explorer 11)
  • crypto.randomBytes (Node.js)

If the platform doesn't provide a suitable PRNG, the following functions, which require random numbers, will throw exception:

  • nacl.randomBytes
  • nacl.box.keyPair
  • nacl.sign.keyPair

Other functions are deterministic and will continue working.

If a platform you are targeting doesn't implement secure random number generator, but you somehow have a cryptographically-strong source of entropy (not Math.random!), and you know what you are doing, you can plug it into TweetNaCl.js like this:

nacl.setPRNG(function(x, n) {
  // ... copy n random bytes into x ...
});

Note that nacl.setPRNG completely replaces internal random byte generator with the one provided.

Constant-time comparison

nacl.verify(x, y)

Compares x and y in constant time and returns true if their lengths are non-zero and equal, and their contents are equal.

Returns false if either of the arguments has zero length, or arguments have different lengths, or their contents differ.

System requirements

TweetNaCl.js supports modern browsers that have a cryptographically secure pseudorandom number generator and typed arrays, including the latest versions of:

  • Chrome
  • Firefox
  • Safari (Mac, iOS)
  • Internet Explorer 11

Other systems:

  • Node.js

Development and testing

Install NPM modules needed for development:

$ npm install

To build minified versions:

$ npm run build

Tests use minified version, so make sure to rebuild it every time you change nacl.js or nacl-fast.js.

Testing

To run tests in Node.js:

$ npm run test-node

By default all tests described here work on nacl.min.js. To test other versions, set environment variable NACL_SRC to the file name you want to test. For example, the following command will test fast minified version:

$ NACL_SRC=nacl-fast.min.js npm run test-node

To run full suite of tests in Node.js, including comparing outputs of JavaScript port to outputs of the original C version:

$ npm run test-node-all

To prepare tests for browsers:

$ npm run build-test-browser

and then open test/browser/test.html (or test/browser/test-fast.html) to run them.

To run tests in both Node and Electron:

$ npm test

Benchmarking

To run benchmarks in Node.js:

$ npm run bench
$ NACL_SRC=nacl-fast.min.js npm run bench

To run benchmarks in a browser, open test/benchmark/bench.html (or test/benchmark/bench-fast.html).

Benchmarks

For reference, here are benchmarks from MacBook Pro (Retina, 13-inch, Mid 2014) laptop with 2.6 GHz Intel Core i5 CPU (Intel) in Chrome 53/OS X, Xiaomi Redmi Note 3 smartphone with 1.8 GHz Qualcomm Snapdragon 650 64-bit CPU (ARM) in Chrome 52/Android, and MacBook Air 2020 with Apple M1 SOC (M1) in Chromium 102/macOS.

nacl.js Intelnacl-fast.js Intelnacl.js ARMnacl-fast.js ARMnacl-fast.js M1
salsa201.3 MB/s128 MB/s0.4 MB/s43 MB/s268 MB/s
poly130513 MB/s171 MB/s4 MB/s52 MB/s248 MB/s
hash4 MB/s34 MB/s0.9 MB/s12 MB/s76 MB/s
secretbox 1K1113 op/s57583 op/s334 op/s14227 op/s54546 op/s
box 1K145 op/s718 op/s37 op/s368 op/s1836 op/s
scalarMult171 op/s733 op/s56 op/s380 op/s1882 op/s
sign77 op/s200 op/s20 op/s61 op/s592 op/s
sign.open39 op/s102 op/s11 op/s31 op/s300 op/s

(You can run benchmarks on your devices by clicking on the links at the bottom of the home page).

In short, with nacl-fast.js and 1024-byte messages you can expect to encrypt and authenticate more than 57000 messages per second on a typical laptop or more than 14000 messages per second on a $170 smartphone, sign about 500 and verify 300 messages per second on a laptop or 60 and 30 messages per second on a smartphone, per CPU core (with Web Workers you can do these operations in parallel), which is good enough for most applications.

Contributors

See AUTHORS.md file.

Third-party libraries based on TweetNaCl.js

Who uses it

Some notable users of TweetNaCl.js are listed on the associated wiki page.

NPM DownloadsLast 30 Days