• Stars
    star
    1,663
  • Rank 28,105 (Top 0.6 %)
  • Language
    JavaScript
  • License
    The Unlicense
  • Created almost 11 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Port of TweetNaCl cryptographic library to JavaScript

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.

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 Intel nacl-fast.js Intel nacl.js ARM nacl-fast.js ARM nacl-fast.js M1
salsa20 1.3 MB/s 128 MB/s 0.4 MB/s 43 MB/s 268 MB/s
poly1305 13 MB/s 171 MB/s 4 MB/s 52 MB/s 248 MB/s
hash 4 MB/s 34 MB/s 0.9 MB/s 12 MB/s 76 MB/s
secretbox 1K 1113 op/s 57583 op/s 334 op/s 14227 op/s 54546 op/s
box 1K 145 op/s 718 op/s 37 op/s 368 op/s 1836 op/s
scalarMult 171 op/s 733 op/s 56 op/s 380 op/s 1882 op/s
sign 77 op/s 200 op/s 20 op/s 61 op/s 592 op/s
sign.open 39 op/s 102 op/s 11 op/s 31 op/s 300 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.

More Repositories

1

captcha

Go package captcha implements generation and verification of image and audio CAPTCHAs.
Go
1,818
star
2

uniuri

Go package uniuri generates random strings good for use in URIs to identify unique objects.
Go
429
star
3

webp-quicklook

[DEPRECATED] QuickLook plugin to generate thumbnails and previews for WebP images
C
281
star
4

siphash

Go implementation of SipHash-2-4, a fast short-input PRF created by Jean-Philippe Aumasson and Daniel J. Bernstein.
Go
258
star
5

semicolon-js

Semicolon.js β€” the most useful JavaScript library for cargo cult programmers
Shell
156
star
6

scrypt-async-js

Fast "async" scrypt implementation in JavaScript
JavaScript
139
star
7

fast-sha256-js

SHA-256, HMAC, HKDF and PBKDF2 implementation for JavaScript/TypeScript with typed arrays for modern browsers and Node.js
JavaScript
123
star
8

authcookie

[DEPRECATED] Go package authcookie implements creation and verification of signed authentication cookies.
Go
110
star
9

blake2b

Go implementation of BLAKE2 (b) cryptographic hash function (optimized for 64-bit platforms).
Go
90
star
10

blake2s-js

BLAKE2s cryptographic hash function in JavaScript
JavaScript
85
star
11

safefile

Go package safefile implements safe "atomic" saving of files.
Go
79
star
12

passwordreset

[DEPRECATED] Go package passwordreset implements creation and verification of secure tokens useful for implementation of "reset forgotten password" feature in web applications.
Go
78
star
13

ellipticlicense

Short product key generation and validation framework based on elliptic curve digital signatures (ECDSA) for Mac OS X/Cocoa. **DEPRECATED**
Objective-C
69
star
14

fossil-delta-js

Fossil SCM delta compression in JavaScript
JavaScript
67
star
15

tweetnacl-util-js

Some string encoding utilities
JavaScript
59
star
16

ed2curve-js

Convert Ed25519 signing keys into Curve25519 Diffie-Hellman keys
JavaScript
56
star
17

stemmer

Stemmer packages for Go programming language. Includes English, German and Dutch stemmers.
Go
50
star
18

pyblake2

Python extension module implementing BLAKE2 hash function
Python
38
star
19

nacl-stream-js

Streaming encryption based on TweetNaCl.js
JavaScript
36
star
20

scrypt

Go package scrypt implements the scrypt key derivation function as defined in Colin Percival's paper "Stronger Key Derivation via Sequential Memory-Hard Functions".
Go
31
star
21

pybayesantispam

Simple Bayesian spam rating in Python that is easy to use, small, contained in a single file, and doesn't require any external modules.
Python
27
star
22

static-search

Simple client-side static search engine (Go indexer, JavaScript searcher).
JavaScript
23
star
23

blake256

Go package blake256 implements BLAKE-256 and BLAKE-224 hash functions (SHA-3 finalist).
Go
20
star
24

tweetnacl-auth-js

HMAC-SHA-512-256 for TweetNacl.js
JavaScript
20
star
25

spipe

Go package spipe implements spiped protocol for creating symmetrically encrypted and authenticated connections.
Go
20
star
26

cryptopass

Chrome extension: password generator from master key using PBKDF2 with SHA-256.
JavaScript
18
star
27

jsmin

Go package to minify JavaScript, which is a direct port of Douglas Crockford's JSMin
Go
17
star
28

historic-password-hashes

Historic password hashing algorithms
C
16
star
29

b2sum

Go implementation of b2sum utility to calculate BLAKE2 checksums (GitHub Mirror)
Go
16
star
30

validator

Go package validator validates and normalizes email addresses and domain names.
Go
16
star
31

drakon-tea

TEA cipher in CBC mode written in DRAKON Editor + C as a fun exercise.
C
14
star
32

tinyscheme

Tiny fork of TinySCHEME to support no-hassle building on Mac OS X (plus a bridge to Objective-C, but use CocoaScheme instead of this) WARNING: NOT UPDATED, OLD
C
14
star
33

minimal-newtab

Chrome Extension: Minimalistic New Tab page that displays bookmarks from Bookmarks Bar and number of new messages in Gmail (including Google Apps).
JavaScript
12
star
34

htmlmin

Go package to minify HTML (alpha-quality)
Go
12
star
35

kkr

Kukuruz - static site generator similar to Jekyll in Go.
Go
11
star
36

blake2s

Go implementation of BLAKE2 (s) cryptographic hash function (optimized for 32-bit platforms).
Go
11
star
37

cache

Go package cache implements LRU (Least Recently Used) cache algorithm. [[ Deprecated, use https://github.com/dchest/lru ]]
Go
11
star
38

nacl

Pure Go implementation of NaCl: Networking and Cryptography Library. USE IMPLEMENTATION FROM go.crypto INSTEAD OF THIS ONE.
Go
11
star
39

bcrypt_pbkdf

Go implementation of bcrypt_pbkdf(3) from OpenBSD
Go
11
star
40

scryptutil

Go reimplementation of Colin Percival's scrypt file encryption utility.
Go
10
star
41

throttled-webrate

Another RateLimit for throttled
Go
10
star
42

uscrypt

Go package uscrypt implements Unix crypt-like password hashing scheme based on scrypt sequential memory-hard key derivation function.
Go
10
star
43

blake512

Go package blake512 implements BLAKE-512 and BLAKE-384 hash functions (SHA-3 finalist).
Go
10
star
44

qlfossil

OS X QuickLook plugin to display Fossil repositories
Objective-C
9
star
45

gotweet

This was the first command-line Twitter client in Go programming language, written two days after the release of Go. IT NO LONGER WORKS BECAUSE TWITTER REMOVED HTTP AUTHENTICATION SUPPORT IN API. Use the one in the link below!
Go
9
star
46

skein

Go implementation of Skein-512 hash function, MAC, and stream cipher.
Go
8
star
47

passwordhash

Go package for safe password hashing and comparison. (THIS PACKAGE IS DEPRECATED! USE bcrypt OR scrypt FROM go.crypto)
Go
8
star
48

hesfic

Content-addressable encrypted storage or something like that
Go
8
star
49

passwordcheck

Go package passwordcheck is a password and passphrase strength checker based on passwdqc.
C
7
star
50

imgpreview

Tiny image previews for HTML while the original image is loading
Go
7
star
51

varuint

Go package varuint implements SQLite4-like variable unsigned integer encoding.
Go
7
star
52

imageutil

Go package imageutil implements functions for the manipulation of images.
Go
7
star
53

ick

Stupid (but fast) static site generator
C
7
star
54

wots

Go package wots implements Winternitz-Lamport-Diffie one-time signature scheme.
Go
7
star
55

cssmin

Go package to minify CSS, which is a direct port of Ryan Grove's cssmin from Ruby
Go
6
star
56

zibr

Repack ZIP or PNG files into Brotli
Go
6
star
57

pbkdf2

Go implementation of PBKDF2 key derivation function. (Modified original from https://bitbucket.org/taruti/pbkdf2.go) DEPRECATED. Please use the one from the official go.crypto repo: http://code.google.com/p/go/source/browse?repo=crypto#hg%2Fpbkdf2
Go
6
star
58

commit-ads

Put your ad into my commit!
5
star
59

blakesum

Utility to calculate BLAKE-224, -256, -385, or -512 checksums.
Go
5
star
60

siv

[WORK-IN-PROGRESS] Go package siv implements Synthetic Initialization Vector (SIV) authenticated encryption using AES (AES-SIV) as specified in RFC 5297
Go
5
star
61

chacha20

Go package chacha20 implements ChaCha stream cipher.
Go
5
star
62

dhgroup14

Go package dhgroup14 implements blinded Diffie-Hellman key agreement with 2048-bit group #14 modulus from RFC 3526.
Go
4
star
63

CocoaScheme

Unfinished Scheme<->Objective-C bridge using s7 Scheme interpreter.
C
4
star
64

osxzip

Functions to compress and decompress ZIP files that preserve Mac OS X resource forks / extended attributes like Apple's Archive Utility.
4
star
65

gimli-js

Gimli permutation and hash implementation in JavaScript
JavaScript
4
star
66

threefish

Go implementation of Threefish-512 block cipher.
Go
4
star
67

comboserver

Comboserver serves multiple files combined in a single request.
Go
4
star
68

blake2xb

Go implementation of BLAKE2Xb XOF
Go
4
star
69

gospiped

spiped and spipe utilities reimplemented in Go
Go
4
star
70

tweets

My Twitter archive
JavaScript
3
star
71

translit.go

Go package translit implements non-standard one-way string transliteration from Cyrillic to Latin.
Go
3
star
72

Dockity

Mac OS X utility that automatically hides or shows dock based on windows positions, just like Ubuntu's Unity. (Click on releases to get binaries)
Objective-C
3
star
73

geli-threefish

geli-threefish is a set of patches for FreeBSD geom-eli and crypto kernel modules to support disk encryption with Threefish-512 algorithm.
C
3
star
74

vim-settings

My OLD .vim and .vimrc. SEE dchest/dotvim FOR A CLEAN START
Vim Script
3
star
75

generatepassword-js

Random password generator in JavaScript for browsers
JavaScript
3
star
76

Utilities

Various utility categories and classes (Objective-C)
Objective-C
3
star
77

godbm

UNMAINTAINED, not written by me. Forked from tux21b to send pull request, but the original seem to be no longer available. /// A simple DBM package for Go
Go
3
star
78

conflag

Drop-in replacement for Go's flag package that reads config files before command-line arguments
Go
3
star
79

dchest.com

My website
HTML
2
star
80

blake2xs

Go implementation of BLAKE2Xs XOF
Go
2
star
81

cmac

CMAC implementation from old Go crypto package converted to modern Go
Go
2
star
82

lua-corweb

Tiny unfinished Lua coroutine-based stateful web framework.
Lua
2
star
83

xaes

JavaScript XAES-256-GCM implementation using Web Cryptography API
JavaScript
2
star
84

dart-blake

BLAKE-256 hash function implementation for Dart language.
Dart
2
star
85

kukuruz

Static site generator similar to jekyll in Go (incomplete, but works). This version is deprecated, please see github.com/dchest/kkr for a new one!
Go
2
star
86

hide-google-plus-bell

Chrome extension to hide Google+ notifications bell (NO LONGER WORKS)
CSS
2
star
87

emacs-settings

My .emacs.d directory and .emacs (symlink it to ~/.emacs.d/emacs)
Emacs Lisp
2
star
88

cgirunner

Simple CGI runner in Go (aka "make nginx run CGIs")
Go
1
star
89

cbrotli

cbrotli without libbrotli
C
1
star
90

Lunokhod

Lua-Cocoa bindings and more (not ready, no longer developed)
C
1
star
91

db-api

PostgreSQL database with API
PLpgSQL
1
star
92

ficly-writes-like

Analyzes ficly.com stories using iwl.me
JavaScript
1
star
93

randomword

Print random word
Go
1
star
94

font-nsa

NSA Smiley Font
CSS
1
star
95

spipe-examples

Examples of using spipe package
Go
1
star
96

onmap

Go package onmap puts pins on a world map image.
Go
1
star
97

password-gen

GUI in Racket for password generator as in http://sellme.ru/p/
Racket
1
star
98

racket-cdb

Racket interface to TinyCDB library
Racket
1
star
99

kdfutil

Some useful key derivation utilities for Go
Go
1
star
100

blake2-dart

BLAKE2s implementation in Dart language.
Dart
1
star