TweetNaCl.js: Cryptographic Library

1.0.3 · active · verified Sun Apr 19

TweetNaCl.js is a JavaScript port of the TweetNaCl/NaCl cryptographic library, designed for modern browsers and Node.js. It provides a thin layer of idiomatic high-level API over a faithful translation of the original C implementation, prioritizing security and correctness. The library ships with two versions: `nacl.js` (a direct port) and `nacl-fast.js` (which includes faster, optimized functions and is used by default when installed via npm). Currently at version 1.0.3, it maintains a stable release cadence with updates typically addressing security fixes or minor improvements. A key differentiator is its public domain license and a comprehensive audit by Cure53 in 2017, which found no security problems, cementing its reputation as a robust and secure cryptographic tool. All API functions operate on `Uint8Array` for byte handling.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates public-key authenticated encryption using `nacl.box`. It covers key pair generation, message encryption, and decryption, highlighting the use of `Uint8Array` for all data operations and the importance of a unique nonce.

import nacl from 'tweetnacl';

// Utility for converting strings to Uint8Array and vice-versa (not part of tweetnacl itself)
const encoder = new TextEncoder();
const decoder = new TextDecoder();

function utf8ToUint8Array(str) {
  return encoder.encode(str);
}

function uint8ArrayToUtf8(arr) {
  return decoder.decode(arr);
}

// Generate a key pair for the sender and receiver
const senderKeyPair = nacl.box.keyPair();
const receiverKeyPair = nacl.box.keyPair();

// A message to encrypt
const message = 'Hello, secure world! This is a secret message.';
const messageUint8 = utf8ToUint8Array(message);

// Generate a random nonce for the encryption
const nonce = nacl.randomBytes(nacl.box.nonceLength);

// Encrypt the message
const encryptedMessage = nacl.box(
  messageUint8,
  nonce,
  receiverKeyPair.publicKey,
  senderKeyPair.secretKey
);

console.log('Original message:', message);
console.log('Encrypted message (Uint8Array):', encryptedMessage);

// Decrypt the message
const decryptedMessageUint8 = nacl.box.open(
  encryptedMessage,
  nonce,
  senderKeyPair.publicKey,
  receiverKeyPair.secretKey
);

if (decryptedMessageUint8) {
  const decryptedMessage = uint8ArrayToUtf8(decryptedMessageUint8);
  console.log('Decrypted message:', decryptedMessage);
} else {
  console.error('Decryption failed!');
}

view raw JSON →