js-nacl: High-level libsodium API

1.4.0 · maintenance · verified Tue Apr 21

js-nacl is a JavaScript library offering a high-level API for libsodium, a well-regarded cryptographic library based on NaCl. It operates by wrapping an Emscripten-compiled version of libsodium, providing robust cryptographic primitives for both Node.js and browser environments. The current stable version, 1.4.0, was released in late 2018 and is based on libsodium 1.0.18-stable. Key differentiators include its adherence to the security-focused libsodium API, cross-platform compatibility, and the use of WebAssembly (WASM) for performance since version 1.3.0. It aims to simplify complex cryptographic tasks, offering functions for encryption, decryption, hashing, and digital signatures. Browser usage requires support for the `window.crypto.getRandomValues` API. The project's release cadence historically followed libsodium updates, with a focus on stability and API consistency, though it has not seen recent updates since 2018.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to instantiate the js-nacl library in Node.js, generate cryptographic keys, nonces, and compute a SHA512 hash using the libsodium API.

const nacl_factory = require('js-nacl/lib/nacl_factory.js');

nacl_factory.instantiate((nacl) => {
  if (!nacl) {
    console.error('Failed to instantiate nacl library.');
    return;
  }

  // Generate a random 32-byte key
  const key = nacl.random_bytes(nacl.crypto_box_SECRETKEYBYTES);
  console.log('Generated key (hex):', nacl.to_hex(key));

  // Example: Generate a random nonce
  const nonce = nacl.random_bytes(nacl.crypto_box_NONCEBYTES);
  console.log('Generated nonce (hex):', nacl.to_hex(nonce));

  // Example: Hash a message
  const message = nacl.from_string('Hello, js-nacl!');
  const hash = nacl.crypto_hash(message);
  console.log('Hashed message (hex):', nacl.to_hex(hash));
});

view raw JSON →