Using Libsodium in PHP Projects

A guide to using the libsodium PHP extension for modern, secure, and fast cryptography. Open Source.

Utilities and Helpers

These functions are useful in general, regardless of which cryptographic utility your application needs.

To view the old API documentation, click here.

Hexadecimal Encoding

string sodium_bin2hex(string $binary)

Libsodium offers a variant of PHP's bin2hex() feature designed to be resistant to side-channel attacks. You can use it just like PHP's bin2hex() function:

$hex_string = sodium_bin2hex($binary_string);

Hexadecimal Decoding

string sodium_hex2bin(string $hex, string $ignore = '')

Similar to above, libsodium also offers a complementary function for the inverse operation.

$binary_string = sodium_hex2bin($hex_string);

Libsodium's hex2bin() also accepts a second optional string argument for characters to ignore. This is useful if, for example, you want to convert an IPv6 address into a raw binary string without the : separators breaking your algorithm.

$binary = sodium_hex2bin($ipv6_addr, ':');

Like sodium_bin2hex(), sodium_hex2bin() is resistant to side-channel attacks while PHP's built-in function is not.

Wiping Sensitive Data from Memory

void sodium_memzero(&string $secret);

When you are done handling sensitive information, use sodium_memzero() to erase the contents of a variable.

Warning: If you're running PHP 7, make sure you're using version 1.0.1 of the PHP extension before using this function.

$ciphertext = sodium_crypto_secretbox($message, $nonce, $key);
sodium_memzero($message);
sodium_memzero($key);

Incrementor for Sequential Nonces

void sodium_increment(&string $binary_string)

If you need to increment a value (e.g. given a randomly generated nonce, obtain the next nonce), use sodium_increment().

$x = random_bytes(sodium_CRYPTO_SECRETBOX_NONCEBYTES);

// After an encryption
sodium_increment($x);

Constant-Time String Comparison

int sodium_compare(string $str1, string $str2)

Timing-safe variant of PHP's native strcmp().

Returns -1 if $str1 is less than $str2; 1 if $str1 is greater than $str2, and 0 if they are equal. This is mostly useful for comparing nonces to prevent replay attacks.

Example:

if (sodium_compare($message['nonce'], $expected_nonce) === 0) {
    // Proceed with crypto_box decryption
}

Constant-Time Memory Equality Comparison

int sodium_memcmp(string $a, string $b)

Compare two strings in constant time. (Similar to hash_equals().)

  • Returns 0 if successful
  • Returns -1 otherwise

Example:

if (sodium_memcmp($mac, $given_mac) !== 0) {
    // Failure
}

Extra Information