Skip to table dataSkip to menuSkip to searchHotkeys reference
Sodium is a modern software library for encryption, digital signature, and password hashing.
PHP 7.2+ incorporates Sodium, enabling relatively simple, extremely secure data exchanges.
Authenticated Encryption with Associated Data (AEAD) AES-256-GCM streamlines the process.

The symmetrical example below generates encrypted text, an encryption key, and a nonce.
The associated data doesn't get encrypted but is required for authentication and decryption.




Sodium also provides low-code asymmetrical Public-Key Encryption methods.

$aliceKeypair = sodium_crypto_box_keypair();
$alicePublicKey = sodium_crypto_box_publickey($aliceKeypair);
$aliceSecretKey = sodium_crypto_box_secretkey($aliceKeypair);

$bobKeypair = sodium_crypto_box_keypair();
$bobPublicKey = sodium_crypto_box_publickey($bobKeypair);
$bobSecretKey = sodium_crypto_box_secretkey($bobKeypair);

$msg = 'Hi Bob, this is Alice!';
$nonce = random_bytes(SODIUM_CRYPTO_BOX_NONCEBYTES);

$keyEncrypt = $aliceSecretKey . $bobPublicKey;
$ciphertext = sodium_crypto_box($msg, $nonce, $keyEncrypt);

$keyDecrypt = $bobSecretKey . $alicePublicKey;
$plaintext = sodium_crypto_box_open($ciphertext, $nonce, $keyDecrypt);