Security News
Research
Data Theft Repackaged: A Case Study in Malicious Wrapper Packages on npm
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
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 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.
Supported browsers/JS engines:
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.
The dist directory contains pre-built scripts. Copy the files from one of its subdirectories to your application:
libsodium-wrappers
is the module your application should load, which
will in turn automatically load libsodium
as a dependency.The modules are also available on npm:
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);
})();
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>
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)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) }
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.
If you want to compile the files yourself, the following dependencies need to be installed on your system:
Running make
will install the dev dependencies, clone libsodium,
build it, test it, build the wrapper, and create the modules and
minified distribution files.
Built by Ahmad Ben Mrad, Frank Denis and Ryan Lester.
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 1,098,284 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
Research
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
Research
Security News
Attackers used a malicious npm package typosquatting a popular ESLint plugin to steal sensitive data, execute commands, and exploit developer systems.
Security News
The Ultralytics' PyPI Package was compromised four times in one weekend through GitHub Actions cache poisoning and failure to rotate previously compromised API tokens.