Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Web and Security

PHP Sodium functions

Reference for PHP's Sodium extension: secretbox encryption, signatures, key exchange, password hashing and constant-time helpers, with safe usage notes.

The Sodium extension wraps the libsodium library. It offers high-level, hard-to-misuse functions for encryption, signing, key exchange and password hashing, and has been bundled with PHP since 7.2. The sodium_* functions pick safe algorithms for you, so there are no cipher names, modes or padding to choose.

On many installations Sodium is enabled, but not on every one: the PHP runner on this site does not include it. Check with extension_loaded('sodium') before relying on it. The examples below are therefore read-only, and the live examples show the same ideas with the always-available alternatives.

PHP
$key = sodium_crypto_secretbox_keygen();
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$box = sodium_crypto_secretbox('message', $nonce, $key);

Try it

Read-only: secret-key encryption and its reverse, as you would write it on a server that has Sodium.

PHP
<?php
$key = sodium_crypto_secretbox_keygen();                 // 32 random bytes
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES); // 24 bytes, new for each message

$box = sodium_crypto_secretbox('Meet me at noon.', $nonce, $key);

// Store nonce + box together.
$stored = base64_encode($nonce . $box);

$raw = base64_decode($stored);
$plain = sodium_crypto_secretbox_open(
    substr($raw, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES),
    substr($raw, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES),
    $key
);

var_dump($plain);          // "Meet me at noon." or false if altered
sodium_memzero($key);      // wipe the key from memory when done
PHP Detect support and fall back safely

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Password hashing without Sodium

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

The most used functions:

Function Purpose
sodium_crypto_secretbox_keygen(), sodium_crypto_secretbox($msg, $nonce, $key), sodium_crypto_secretbox_open($box, $nonce, $key) Encrypt and authenticate with one shared key (XSalsa20-Poly1305). Open returns false on failure.
sodium_crypto_box_keypair(), sodium_crypto_box($msg, $nonce, $keypair) Public-key encryption between two parties.
sodium_crypto_sign_keypair(), sodium_crypto_sign_detached($msg, $secretKey), sodium_crypto_sign_verify_detached($sig, $msg, $publicKey) Digital signatures (Ed25519).
sodium_crypto_pwhash_str($password, $opslimit, $memlimit), sodium_crypto_pwhash_str_verify($hash, $password) Argon2id password hashes.
sodium_crypto_generichash($msg, $key = '', $length = 32) Fast keyed or unkeyed hash (BLAKE2b).
sodium_memzero(&$string), sodium_compare($a, $b), sodium_bin2hex($bin) Constant-time and memory-safety helpers.
sodium_crypto_aead_xchacha20poly1305_ietf_encrypt(...) Authenticated encryption with additional data.

Errors: wrong key or nonce lengths throw SodiumException. Failed authentication in the *_open functions returns false.

Usage notes

  • One nonce per message per key. With secretbox it can be random (24 bytes is large enough). Store it beside the ciphertext.
  • Always test for false from *_open functions. It means the message was altered or the key is wrong.
  • Keys are binary, not text. Use sodium_bin2hex() or base64_encode() to store them.
  • sodium_crypto_pwhash_str() and password_hash() with PASSWORD_ARGON2ID produce compatible-looking Argon2id strings. In most apps password_hash() is simpler.
  • Memory: sodium_memzero() overwrites a string in place; it only helps when no other copies exist.
  • Compared with OpenSSL, Sodium has fewer knobs and fewer foot-guns. See openssl_encrypt() when Sodium is missing.
  • Polyfill: the paragonie/sodium_compat Composer package provides a slower pure-PHP version for hosts without the extension.