Convert Figma logo to code with AI

jedisct1 logolibsodium.js

libsodium compiled to Webassembly and pure JavaScript, with convenient wrappers.

1,045
147
1,045
2

Top Related Projects

5,205

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

7,223

Stanford Javascript Crypto Library

16,187

JavaScript library of crypto standards.

Port of TweetNaCl cryptographic library to JavaScript

Fast Elliptic Curve Cryptography in plain javascript

Quick Overview

Libsodium.js is a JavaScript port of the Libsodium cryptography library. It provides a set of easy-to-use, high-level cryptographic APIs for encryption, decryption, signatures, password hashing, and more. This library allows developers to implement secure cryptographic operations in web applications running in browsers or Node.js environments.

Pros

  • Easy-to-use, high-level API for common cryptographic operations
  • Cross-platform compatibility (works in browsers and Node.js)
  • Constant-time implementations to mitigate timing attacks
  • Actively maintained and regularly updated

Cons

  • Larger file size compared to some other cryptographic libraries
  • May have a steeper learning curve for developers new to cryptography
  • Limited to the algorithms and operations provided by Libsodium

Code Examples

  1. Generating a random key:
const key = sodium.crypto_secretbox_keygen();
console.log(sodium.to_hex(key));
  1. Encrypting a message:
const message = 'Hello, Libsodium!';
const nonce = sodium.randombytes_buf(sodium.crypto_secretbox_NONCEBYTES);
const ciphertext = sodium.crypto_secretbox_easy(message, nonce, key);
console.log(sodium.to_hex(ciphertext));
  1. Decrypting a message:
const decrypted = sodium.crypto_secretbox_open_easy(ciphertext, nonce, key);
console.log(sodium.to_string(decrypted));
  1. Hashing a password:
const password = 'mySecurePassword123';
const hashedPassword = sodium.crypto_pwhash_str(
  password,
  sodium.crypto_pwhash_OPSLIMIT_INTERACTIVE,
  sodium.crypto_pwhash_MEMLIMIT_INTERACTIVE
);
console.log(hashedPassword);

Getting Started

To use Libsodium.js in your project, follow these steps:

  1. Install the library using npm:
npm install libsodium-wrappers
  1. Import and initialize the library in your JavaScript code:
import { ready, sodium } from 'libsodium-wrappers';

async function main() {
  await ready;
  // Your code using sodium goes here
}

main();
  1. Start using the cryptographic functions provided by the sodium object, as shown in the code examples above.

Competitor Comparisons

5,205

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

Pros of Forge

  • Pure JavaScript implementation, making it easier to use in various JavaScript environments
  • Broader range of cryptographic functions and utilities
  • More extensive documentation and examples

Cons of Forge

  • Generally slower performance compared to libsodium.js
  • Less focus on modern, high-security algorithms
  • Larger file size, which may impact load times in web applications

Code Comparison

Forge (RSA key generation):

var rsa = forge.pki.rsa;
var keypair = rsa.generateKeyPair({bits: 2048, e: 0x10001});

libsodium.js (Public-key cryptography):

var keyPair = sodium.crypto_box_keypair();
var publicKey = keyPair.publicKey;
var privateKey = keyPair.privateKey;

Forge provides a more traditional approach to cryptography, with support for older algorithms like RSA. libsodium.js focuses on modern, high-security algorithms and offers a simpler API for common cryptographic operations. While Forge is more flexible and feature-rich, libsodium.js generally provides better performance and stronger security guarantees out of the box.

7,223

Stanford Javascript Crypto Library

Pros of SJCL

  • Pure JavaScript implementation, making it easier to integrate into web projects
  • Broader range of cryptographic primitives and operations
  • More extensive documentation and examples

Cons of SJCL

  • Less actively maintained compared to libsodium.js
  • May have lower performance for certain operations
  • Lacks some modern cryptographic algorithms and constructions

Code Comparison

SJCL encryption:

var ciphertext = sjcl.encrypt("password", "message");

libsodium.js encryption:

var ciphertext = sodium.crypto_secretbox_easy(message, nonce, key);

Both libraries offer encryption functionality, but libsodium.js requires separate handling of nonce and key, while SJCL combines these elements in a single function call.

SJCL provides a higher-level API that may be more user-friendly for beginners, while libsodium.js offers more granular control over cryptographic operations.

libsodium.js is generally considered more up-to-date and secure, benefiting from the audited C implementation of libsodium. However, SJCL's pure JavaScript approach may be preferable in certain scenarios where importing external libraries is not feasible.

For modern web applications requiring state-of-the-art cryptography, libsodium.js is often the recommended choice. SJCL remains a viable option for projects with specific requirements or those already using its ecosystem.

16,187

JavaScript library of crypto standards.

Pros of crypto-js

  • Wider range of cryptographic algorithms and functions
  • Pure JavaScript implementation, no external dependencies
  • Easier to use for basic cryptographic operations

Cons of crypto-js

  • Less focus on modern, secure cryptographic primitives
  • Not actively maintained, with fewer updates and security audits
  • Potentially slower performance for certain operations

Code Comparison

crypto-js:

var encrypted = CryptoJS.AES.encrypt("Message", "Secret Passphrase");
var decrypted = CryptoJS.AES.decrypt(encrypted, "Secret Passphrase");
console.log(decrypted.toString(CryptoJS.enc.Utf8));

libsodium.js:

var key = sodium.crypto_secretbox_keygen();
var nonce = sodium.randombytes_buf(sodium.crypto_secretbox_NONCEBYTES);
var encrypted = sodium.crypto_secretbox_easy("Message", nonce, key);
var decrypted = sodium.crypto_secretbox_open_easy(encrypted, nonce, key);
console.log(sodium.to_string(decrypted));

Summary

crypto-js offers a broader range of cryptographic functions and is easier to use for basic operations. However, libsodium.js focuses on modern, secure cryptographic primitives and is more actively maintained. libsodium.js also provides better performance for certain operations and has undergone more rigorous security audits. The choice between the two libraries depends on specific project requirements, security needs, and the level of cryptographic expertise required.

Port of TweetNaCl cryptographic library to JavaScript

Pros of TweetNaCl-js

  • Smaller library size, making it more suitable for lightweight applications
  • Pure JavaScript implementation, ensuring easier integration and portability
  • Simpler API with fewer functions, potentially easier to learn and use

Cons of TweetNaCl-js

  • Limited feature set compared to Libsodium.js
  • Fewer cryptographic primitives and algorithms available
  • Less frequent updates and maintenance

Code Comparison

TweetNaCl-js:

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

Libsodium.js:

const sodium = require('libsodium-wrappers');
await sodium.ready;
const message = new Uint8Array([1, 2, 3, 4]);
const nonce = sodium.randombytes_buf(sodium.crypto_secretbox_NONCEBYTES);
const key = sodium.crypto_secretbox_keygen();
const encrypted = sodium.crypto_secretbox_easy(message, nonce, key);

Both libraries provide similar functionality for basic cryptographic operations, but Libsodium.js offers a more extensive set of features and a slightly different API structure. TweetNaCl-js is more compact and straightforward, while Libsodium.js provides a broader range of cryptographic primitives and algorithms.

Fast Elliptic Curve Cryptography in plain javascript

Pros of elliptic

  • Focused specifically on elliptic curve cryptography, offering a wide range of curve implementations
  • Lightweight and modular design, allowing users to include only needed components
  • Well-documented API with extensive examples and usage instructions

Cons of elliptic

  • Narrower scope compared to libsodium.js, which offers a broader range of cryptographic primitives
  • Less actively maintained, with fewer recent updates and contributions
  • May require additional libraries for certain cryptographic operations not covered by elliptic curves

Code Comparison

elliptic:

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

libsodium.js:

const sodium = require('libsodium-wrappers');
await sodium.ready;
const keyPair = sodium.crypto_sign_keypair();
const signature = sodium.crypto_sign_detached(message, keyPair.privateKey);
console.log(sodium.to_hex(signature));

Both libraries provide cryptographic functionality, but elliptic focuses on elliptic curve operations while libsodium.js offers a broader range of cryptographic primitives. elliptic's API is more specific to elliptic curve operations, while libsodium.js provides a more comprehensive set of cryptographic functions with a consistent API across different operations.

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

libsodium.js

Overview

The sodium crypto library compiled to WebAssembly and pure JavaScript using Emscripten, with automatically generated wrappers to make it easy to use in web applications.

The complete library weighs 188 KB (minified, gzipped, includes pure JS + WebAssembly versions) and can run in a web browser as well as server-side.

Compatibility

Supported browsers/JS engines:

  • Chrome >= 16
  • Edge >= 0.11
  • Firefox >= 21
  • Mobile Safari on iOS >= 8.0 (older versions produce incorrect results)
  • NodeJS
  • Bun
  • Opera >= 15
  • Safari >= 6 (older versions produce incorrect results)

This is comparable to the WebCrypto API, which is compatible with a similar number of browsers.

Signatures and other Edwards25519-based operations are compatible with WasmCrypto.

Installation

The dist directory contains pre-built scripts. Copy the files from one of its subdirectories to your application:

  • browsers includes a single-file script that can be included in web pages. It contains code for commonly used functions.
  • browsers-sumo is a superset of the previous script, that contains all functions, including rarely used ones and undocumented ones.
  • modules includes commonly used functions, and is designed to be loaded as a module. libsodium-wrappers is the module your application should load, which will in turn automatically load libsodium as a dependency.
  • modules-sumo contains sumo variants of the previous modules.

The modules are also available on npm:

Usage (as a module)

Load the libsodium-wrappers module. The returned object contains a .ready property: a promise that must be resolve before the sodium functions can be used.

Example:

import _sodium from 'libsodium-wrappers';
await (async() => {
  await _sodium.ready;
  const sodium = _sodium;

  let key = sodium.crypto_secretstream_xchacha20poly1305_keygen();

  let res = sodium.crypto_secretstream_xchacha20poly1305_init_push(key);
  let [state_out, header] = [res.state, res.header];
  let c1 = sodium.crypto_secretstream_xchacha20poly1305_push(state_out,
    sodium.from_string('message 1'), null,
    sodium.crypto_secretstream_xchacha20poly1305_TAG_MESSAGE);
  let c2 = sodium.crypto_secretstream_xchacha20poly1305_push(state_out,
    sodium.from_string('message 2'), null,
    sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL);

  let state_in = sodium.crypto_secretstream_xchacha20poly1305_init_pull(header, key);
  let r1 = sodium.crypto_secretstream_xchacha20poly1305_pull(state_in, c1);
  let [m1, tag1] = [sodium.to_string(r1.message), r1.tag];
  let r2 = sodium.crypto_secretstream_xchacha20poly1305_pull(state_in, c2);
  let [m2, tag2] = [sodium.to_string(r2.message), r2.tag];

  console.log(m1);
  console.log(m2);
})();

Usage (in a web browser, via a callback)

The sodium.js file includes both the core libsodium functions, as well as the higher-level JavaScript wrappers. It can be loaded asynchronusly.

A sodium object should be defined in the global namespace, with the following property:

  • onload: the function to call after the wrapper is initialized.

Example:

<script>
    window.sodium = {
        onload: function (sodium) {
            let h = sodium.crypto_generichash(64, sodium.from_string('test'));
            console.log(sodium.to_hex(h));
        }
    };
</script>
<script src="sodium.js" async></script>

Additional helpers

  • from_base64(), to_base64() with an optional second parameter whose value is one of: base64_variants.ORIGINAL, base64_variants.ORIGINAL_NO_PADDING, base64_variants.URLSAFE or base64_variants.URLSAFE_NO_PADDING. Default is base64_variants.URLSAFE_NO_PADDING.
  • from_hex(), to_hex()
  • from_string(), to_string()
  • pad(<buffer>, <block size>), unpad(<buffer>, <block size>)
  • memcmp() (constant-time check for equality, returns true or false)
  • compare() (constant-time comparison. Values must have the same size. Returns -1, 0 or 1)
  • memzero() (applies to Uint8Array objects)
  • increment() (increments an arbitrary-long number stored as a little-endian Uint8Array - typically to increment nonces)
  • add() (adds two arbitrary-long numbers stored as little-endian Uint8Array vectors)
  • is_zero() (constant-time, checks Uint8Array objects for all zeros)

API

The API exposed by the wrappers is identical to the one of the C library, except that buffer lengths never need to be explicitly given.

Binary input buffers should be Uint8Array objects. However, if a string is given instead, the wrappers will automatically convert the string to an array containing a UTF-8 representation of the string.

Example:

var key = sodium.randombytes_buf(sodium.crypto_shorthash_KEYBYTES),
    hash1 = sodium.crypto_shorthash(new Uint8Array([1, 2, 3, 4]), key),
    hash2 = sodium.crypto_shorthash('test', key);

If the output is a unique binary buffer, it is returned as a Uint8Array object.

Example (secretbox):

let key = sodium.from_hex('724b092810ec86d7e35c9d067702b31ef90bc43a7b598626749914d6a3e033ed');

function encrypt_and_prepend_nonce(message) {
    let nonce = sodium.randombytes_buf(sodium.crypto_secretbox_NONCEBYTES);
    return nonce.concat(sodium.crypto_secretbox_easy(message, nonce, key));
}

function decrypt_after_extracting_nonce(nonce_and_ciphertext) {
    if (nonce_and_ciphertext.length < sodium.crypto_secretbox_NONCEBYTES + sodium.crypto_secretbox_MACBYTES) {
        throw "Short message";
    }
    let nonce = nonce_and_ciphertext.slice(0, sodium.crypto_secretbox_NONCEBYTES),
        ciphertext = nonce_and_ciphertext.slice(sodium.crypto_secretbox_NONCEBYTES);
    return sodium.crypto_secretbox_open_easy(ciphertext, nonce, key);
}

In addition, the from_hex, to_hex, from_string, and to_string functions are available to explicitly convert hexadecimal, and arbitrary string representations from/to Uint8Array objects.

Functions returning more than one output buffer are returning them as an object. For example, the sodium.crypto_box_keypair() function returns the following object:

{ keyType: 'curve25519', privateKey: (Uint8Array), publicKey: (Uint8Array) }

Standard vs Sumo version

The standard version (in the dist/browsers and dist/modules directories) contains the high-level functions, and is the recommended one for most projects.

Alternatively, the "sumo" version, available in the dist/browsers-sumo and dist/modules-sumo directories contains all the symbols from the original library. This includes undocumented, untested, deprecated, low-level and easy to misuse functions.

The crypto_pwhash_* function set is only included in the sumo version.

The sumo version is slightly larger than the standard version, reserves more memory, and should be used only if you really need the extra symbols it provides.

Compilation

If you want to compile the files yourself, the following dependencies need to be installed on your system:

  • Emscripten
  • binaryen
  • git
  • bun
  • make

Running make will install the dev dependencies, clone libsodium, build it, test it, build the wrapper, and create the modules and minified distribution files.

Related projects

Authors

Built by Ahmad Ben Mrad, Frank Denis and Ryan Lester.

License

This wrapper is distributed under the ISC License.

NPM DownloadsLast 30 Days