<?php
// La $key debe ser mantenida confidencial
$key = random_bytes(SODIUM_CRYPTO_SECRETBOX_KEYBYTES);
// No reutilizar $nonce con la misma clave
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$ciphertext = sodium_crypto_secretbox('mensaje a ser cifrado', $nonce, $key);
// El mismo nonce y la misma clave son necesarios para desencriptar el $ciphertext
$plaintext = sodium_crypto_secretbox_open($ciphertext, $nonce, $key);
if ($plaintext !== false) {
echo $plaintext . PHP_EOL;
}
?>
El resultado del ejemplo sería: