What is libsodium-wrappers?
libsodium-wrappers is a JavaScript wrapper for the Sodium cryptographic library, providing a wide range of cryptographic operations including encryption, decryption, hashing, and key generation. It is designed to be easy to use and secure, making it suitable for both beginners and advanced users.
What are libsodium-wrappers's main functionalities?
Encryption and Decryption
This feature allows you to encrypt and decrypt messages using secret-key cryptography. The code sample demonstrates generating a key and nonce, encrypting a message, and then decrypting it back to its original form.
const sodium = require('libsodium-wrappers');
(async() => {
await sodium.ready;
const key = sodium.crypto_secretbox_keygen();
const nonce = sodium.randombytes_buf(sodium.crypto_secretbox_NONCEBYTES);
const message = 'Hello, World!';
const ciphertext = sodium.crypto_secretbox_easy(message, nonce, key);
const decrypted = sodium.crypto_secretbox_open_easy(ciphertext, nonce, key);
console.log(sodium.to_string(decrypted)); // 'Hello, World!'
})();
Hashing
This feature provides hashing capabilities. The code sample shows how to hash a message using the crypto_generichash function and then convert the hash to a hexadecimal string.
const sodium = require('libsodium-wrappers');
(async() => {
await sodium.ready;
const message = 'Hello, World!';
const hash = sodium.crypto_generichash(32, message);
console.log(sodium.to_hex(hash));
})();
Key Generation
This feature allows you to generate public and private key pairs. The code sample demonstrates generating a key pair and printing the public and private keys in hexadecimal format.
const sodium = require('libsodium-wrappers');
(async() => {
await sodium.ready;
const keyPair = sodium.crypto_box_keypair();
console.log(sodium.to_hex(keyPair.publicKey));
console.log(sodium.to_hex(keyPair.privateKey));
})();
Other packages similar to libsodium-wrappers
crypto-js
crypto-js is a widely-used library that provides standard and secure cryptographic algorithms for JavaScript. It offers functionalities like encryption, decryption, hashing, and more. Compared to libsodium-wrappers, crypto-js is more focused on providing a broad range of cryptographic algorithms but may not be as optimized for performance and security.
tweetnacl
tweetnacl is a cryptographic library that provides high-level cryptographic operations, including public-key encryption, secret-key encryption, and hashing. It is designed to be small, fast, and secure. Compared to libsodium-wrappers, tweetnacl is more lightweight but offers fewer features and less flexibility.
node-forge
node-forge is a comprehensive library for implementing various cryptographic operations in JavaScript. It includes support for public-key cryptography, symmetric-key cryptography, and more. Compared to libsodium-wrappers, node-forge offers a broader range of cryptographic functionalities but may be more complex to use.
libsodium.js
Overview
The sodium crypto library compiled
to pure JavaScript using Emscripten,
with automatically generated wrappers to make it easy to use in web
applications.
The complete library weights 151 Kb (minified, gzipped) and can run in
a web browser as well as server-side.
Compatibility
Supported browsers/JS engines:
- Chrome >= 16
- Edge >= 0.11
- Firefox >= 21
- Internet Explorer >= 11
- Mobile Safari on iOS >= 8.0 (older versions produce incorrect results)
- NodeJS
- Opera >= 15
- Safari >= 6 (older versions produce incorrect results)
Installation
Ready-to-use files based on libsodium 1.0.5 can be directly copied to your
project.
Usage with global definitions, for web browsers
Use Bower:
$ bower install libsodium.js
or directly include a copy of the
sodium.min.js
file.
Including the sodium.min.js
file will add a sodium
object to the
global namespace.
If a sodium
object is already present in the global namespace, and
the sodium.onload
function is defined, this function will be called
right after the library has been loaded and initialized.
<script>
window.sodium = { onload: function(sodium) {
alert(sodium.to_hex(sodium.crypto_generichash(64, 'test')));
}};
</script>
...
<script src="sodium.js" async defer></script>
As an alternative, use a module loader or Browserify as described below.
Usage with CommonJS/AMD/ES6 import
Copy the .js
files for libsodium and libsodium-wrappers
to your project and load the libsodium-wrappers
module.
Alternatively, use npm. The npm package is
called libsodium-wrappers
and includes a dependency on the raw
libsodium
module.
var sodium = require('libsodium-wrappers');
console.log(sodium.to_hex(sodium.crypto_generichash(64, 'test')));
List of wrapped algorithms and functions:
Additional helpers
from_base64()
, to_base64()
from_hex()
, to_hex()
from_string()
, to_string()
memcmp()
(constant-time check for equality, returns true
or false
)compare() (constant-time comparison. Values must have the same size. Returns
-1,
0or
1`)memzero()
(applies to Uint8Array
objects)increment()
(increments an arbitrary-long number stored as a
little-endian Uint8Array
- typically to increment nonces)
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.
However, an extra parameter can be given to all wrapped functions, in
order to specify what format the output should be in. Valid options
are `uint8array' (default), 'text', 'hex' and 'base64'.
Example:
var key = sodium.randombytes_buf(sodium.crypto_shorthash_KEYBYTES),
hash_hex = sodium.crypto_shorthash('test', key, 'hex');
In addition, the from_base64
, to_base64
, from_hex
, to_hex
,
from_string
, and to_string
functions are available to explicitly
convert base64, 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) }
Compilation
If you want to compile the files yourself, the following dependencies
need to be installed on your system:
- autoconf
- automake
- emscripten
- git
- nodejs
- libtool
- make
- mocha (
npm install -g mocha
) - zopfli (
npm install -g node-zopfli
)
Running make
will clone libsodium, build it, test it, build the
wrapper, and create the modules and minified distribution files.
Custom build
The build available in this repository does not contain all the functions available in the original libsodium library.
Providing that you have all the build dependencies installed, here is how you can build libsodium.js to include the functions you need :
git clone https://github.com/jedisct1/libsodium.js
cd ./libsodium.js
# Get the original C version of libsodium and configure it
make libsodium/configure
# Modify the emscripten.sh
# Specifically, add the name of the missing functions and constants in the "EXPORTED_FUNCTIONS" array.
# Ensure that the name begins with an underscore and that it is between double quotes.
nano libsodium/dist-build/emscripten.sh
# Build libsodium, and then libsodium.js with your chosen functions
make
NOTE: for each of the functions/constants you add, make sure that the corresponding symbol files exist in the wrapper/symbols
folder and that the constants are listed in the wrapper/constants.json
file.
Authors
Built by Ahmad Ben Mrad and Frank Denis.
License
This wrapper is distributed under the
ISC License.