Security News
GitHub Removes Malicious Pull Requests Targeting Open Source Repositories
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
libsodium-wrappers-sumo
Advanced tools
The Sodium cryptographic library compiled to pure JavaScript (wrappers, sumo variant)
libsodium-wrappers-sumo is a JavaScript wrapper for the Sodium cryptographic library, providing a wide range of cryptographic operations. It includes additional features from the 'sumo' variant of libsodium, which offers extended functionalities beyond the standard libsodium library.
Symmetric Encryption
This feature allows you to encrypt a message using symmetric encryption. The code generates a random key and nonce, then encrypts the message 'Hello, World!' using the crypto_secretbox_easy function.
const sodium = require('libsodium-wrappers-sumo');
(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);
console.log({ nonce, ciphertext });
})();
Asymmetric Encryption
This feature allows you to encrypt a message using asymmetric encryption. The code generates a key pair, a random nonce, and then encrypts the message 'Hello, World!' using the crypto_box_easy function.
const sodium = require('libsodium-wrappers-sumo');
(async() => {
await sodium.ready;
const { publicKey, privateKey } = sodium.crypto_box_keypair();
const nonce = sodium.randombytes_buf(sodium.crypto_box_NONCEBYTES);
const message = 'Hello, World!';
const ciphertext = sodium.crypto_box_easy(message, nonce, publicKey, privateKey);
console.log({ nonce, ciphertext });
})();
Hashing
This feature allows you to hash a message. The code hashes the message 'Hello, World!' using the crypto_generichash function, producing a 32-byte hash.
const sodium = require('libsodium-wrappers-sumo');
(async() => {
await sodium.ready;
const message = 'Hello, World!';
const hash = sodium.crypto_generichash(32, message);
console.log({ hash });
})();
Digital Signatures
This feature allows you to create a digital signature for a message. The code generates a key pair and then signs the message 'Hello, World!' using the crypto_sign function.
const sodium = require('libsodium-wrappers-sumo');
(async() => {
await sodium.ready;
const { publicKey, privateKey } = sodium.crypto_sign_keypair();
const message = 'Hello, World!';
const signature = sodium.crypto_sign(message, privateKey);
console.log({ signature });
})();
TweetNaCl is a cryptographic library that provides similar functionalities to libsodium-wrappers-sumo, such as public-key encryption, secret-key encryption, and hashing. However, it is a smaller library with fewer features and does not include the extended functionalities found in the 'sumo' variant of libsodium.
CryptoJS is a JavaScript library of crypto standards. It provides a variety of cryptographic algorithms, including AES, SHA-256, and HMAC. While it offers a broad range of cryptographic functions, it does not provide the same level of low-level cryptographic primitives and extended functionalities as libsodium-wrappers-sumo.
Node-forge is a native implementation of TLS in JavaScript and a set of cryptographic utilities. It provides functionalities such as public-key encryption, symmetric encryption, and hashing. Compared to libsodium-wrappers-sumo, node-forge is more focused on providing a comprehensive set of tools for working with TLS and X.509 certificates.
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 110 Kb (minified, gzipped) and can run in a web browser as well as server-side.
Supported browsers/JS engines:
Ready-to-use files based on libsodium 1.0.11 can be directly copied to your project.
Use Bower:
$ bower install libsodium.js
or directly include a copy of the sodium.min.js file.
Alternatively, for better performance and to avoid including a local copy, libsodium.js is available on cdnjs.
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.
Copy the .js
files for libsodium and libsodium-wrappers
to your project and load the libsodium-wrappers
module.
Alternatively, use yarn. The Yarn package is
called libsodium-wrappers
and includes a dependency on the raw
libsodium
module.
$ yarn add libsodium-wrappers
var sodium = require('libsodium-wrappers');
console.log(sodium.to_hex(sodium.crypto_generichash(64, 'test')));
crypto_aead
(ChaCha20-Poly1305)crypto_auth
(HMAC-SHA-512-256)crypto_box
crypto_box_seal
crypto_generichash
(Blake2b)crypto_hash
(SHA-512-256)crypto_onetimeauth
(Poly1305)crypto_pwhash
(Argon2)crypto_scalarmult
(Curve25519)crypto_secretbox
crypto_shorthash
(SipHash)crypto_sign
(Ed25519)randombytes
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)add()
(adds two arbitrary-long numbers stored as little-endian
Uint8Array
vectors)is_zero()
(constant-time, checks Uint8Array
objects for all zeros)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' and 'hex'.
Example (shorthash):
var key = sodium.randombytes_buf(sodium.crypto_shorthash_KEYBYTES),
hash_hex = sodium.crypto_shorthash('test', key, 'hex');
Example (secretbox):
// Load your secret key from a safe place and reuse it across multiple
// secretbox calls. (Obviously don't use this example key for anything
// real.)
//
var secret = Buffer.from('724b092810ec86d7e35c9d067702b31ef90bc43a7b598626749914d6a3e033ed', 'hex');
// Given a message as a string, return a Buffer containing the
// nonce (in the first 24 bytes) and the encrypted content.
var encrypt = function(message) {
// You must use a different nonce for each message you encrypt.
var nonce = Buffer.from(sodium.randombytes_buf(sodium.crypto_box_NONCEBYTES));
var buf = Buffer.from(message);
return Buffer.concat([nonce, Buffer.from(sodium.crypto_secretbox_easy(buf, nonce, secret))]);
},
// Decrypt takes a Buffer and returns the decrypted message as plain text.
var decrypt = function(encryptedBuffer) {
var nonce = encryptedBuffer.slice(0, sodium.crypto_box_NONCEBYTES);
var encryptedMessage = encryptedBuffer.slice(sodium.crypto_box_NONCEBYTES);
return sodium.crypto_secretbox_open_easy(encryptedMessage, nonce, secret, 'text');
}
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) }
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 also only included in the Sumo
version. The high amount of heap memory (allocated after loading) required by
these functions may not be desirable when they are not being used.
The sumo version is slightly larger than the standard version, and should be used only if you really need the extra symbols it provides.
If you want to compile the files yourself, the following dependencies need to be installed on your system:
yarn global add node-zopfli
)yarn global add uglify-js
)Running make
will clone libsodium, build it, test it, build the
wrapper, and create the modules and minified distribution files.
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.
Built by Ahmad Ben Mrad and Frank Denis.
This wrapper is distributed under the ISC License.
FAQs
The Sodium cryptographic library compiled to pure JavaScript (wrappers, sumo variant)
We found that libsodium-wrappers-sumo demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.