Security News
ESLint is Now Language-Agnostic: Linting JSON, Markdown, and Beyond
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
The Sodium cryptographic library compiled to pure JavaScript (raw library, no wrappers)
libsodium is a modern, easy-to-use software library for encryption, decryption, signatures, password hashing, and more. It is designed to be a portable, cross-compilable, installable, and packageable fork of NaCl, with a compatible API.
Public Key Cryptography
This feature allows you to perform public key cryptography operations such as encryption and decryption. The code sample demonstrates generating a key pair, encrypting a message, and logging the ciphertext and nonce.
const sodium = require('libsodium-wrappers');
(async() => {
await sodium.ready;
const keyPair = sodium.crypto_box_keypair();
const message = 'Hello, World!';
const nonce = sodium.randombytes_buf(sodium.crypto_box_NONCEBYTES);
const cipherText = sodium.crypto_box_easy(message, nonce, keyPair.publicKey, keyPair.privateKey);
console.log({ cipherText, nonce });
})();
Secret Key Cryptography
This feature allows you to perform secret key cryptography operations such as encryption and decryption. The code sample demonstrates generating a key, encrypting a message, and logging the ciphertext and nonce.
const sodium = require('libsodium-wrappers');
(async() => {
await sodium.ready;
const key = sodium.randombytes_buf(sodium.crypto_secretbox_KEYBYTES);
const nonce = sodium.randombytes_buf(sodium.crypto_secretbox_NONCEBYTES);
const message = 'Hello, World!';
const cipherText = sodium.crypto_secretbox_easy(message, nonce, key);
console.log({ cipherText, nonce });
})();
Password Hashing
This feature allows you to hash passwords securely. The code sample demonstrates hashing a password and logging the hashed password.
const sodium = require('libsodium-wrappers');
(async() => {
await sodium.ready;
const password = 'mysecretpassword';
const hashedPassword = sodium.crypto_pwhash_str(password, sodium.crypto_pwhash_OPSLIMIT_INTERACTIVE, sodium.crypto_pwhash_MEMLIMIT_INTERACTIVE);
console.log({ hashedPassword });
})();
Digital Signatures
This feature allows you to create and verify digital signatures. The code sample demonstrates generating a key pair, signing a message, and logging the signed message.
const sodium = require('libsodium-wrappers');
(async() => {
await sodium.ready;
const keyPair = sodium.crypto_sign_keypair();
const message = 'Hello, World!';
const signedMessage = sodium.crypto_sign(message, keyPair.privateKey);
console.log({ signedMessage });
})();
The 'crypto' module in Node.js provides cryptographic functionality that includes a set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions. It is built into Node.js and does not require additional installation. While it offers a wide range of cryptographic operations, it may not be as user-friendly or modern as libsodium.
TweetNaCl is a cryptographic library that is a port of the Networking and Cryptography library (NaCl) to JavaScript. It is designed to be small, fast, and easy to use. While it offers similar functionalities to libsodium, it may lack some of the advanced features and optimizations found in libsodium.
bcrypt is a password hashing function designed for secure password storage. It is widely used and well-tested, but it is specialized for password hashing and does not offer the broader range of cryptographic functionalities that libsodium provides.
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 133 Kb (minified, gzipped) and can run in a web browser as well as server-side.
Ready-to-use files based on libsodium 1.0.2 can be directly copied to your project.
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>
Alternatively, one can load it as a RequireJS module and use Browserify.
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')));
crypto_aead
(ChaCha20-Poly1305)crypto_auth
(SHA256, SHA512, and the default crypto_auth with SHA512/256)crypto_box
crypto_generichash
(Blake2b)crypto_hash
(SHA512/256)crypto_pwhash
(scrypt)crypto_scalarmult
(Curve25519)crypto_secretbox
crypto_shorthash
(SipHash)crypto_sign
(Ed25519)randombytes
from_base64()
, to_base64()
from_hex()
, to_hex()
memcmp()
(constant-time comparison, returns true
or false
)memzero()
(applies to Uint8Array
objects)The API exposed by the wrappers is identical to the one of the C library, except that buffer lengths never need to be explicitely 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
and to_hex
functions are available to explicitly convert base64 and hexadecimal
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) }
If you want to compile the files yourself, the following dependencies need to be installed on your system:
npm install -g mocha
)Running make
will clone libsodium, build it, test it, build the
wrapper, and create the modules and minified distribution files.
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 (raw library, no wrappers)
The npm package libsodium receives a total of 680,741 weekly downloads. As such, libsodium popularity was classified as popular.
We found that libsodium 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
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
Security News
Members Hub is conducting large-scale campaigns to artificially boost Discord server metrics, undermining community trust and platform integrity.
Security News
NIST has failed to meet its self-imposed deadline of clearing the NVD's backlog by the end of the fiscal year. Meanwhile, CVE's awaiting analysis have increased by 33% since June.