[PHP-NOTES] note 130817 added to function.sodium-crypto-secretbox

[email protected] ("Anonymous") Wed, 10 Jun 2026 12:13:28 +0000
Newsgroups php.notes
Message-ID <[email protected]>
A typical safe pattern is to generate both the key and nonce, then store or transmit the nonce alongside the ciphertext.

<?php

// Generate a random key (must be kept secret)
$key = sodium_crypto_secretbox_keygen();

// Generate a unique nonce for this message (24 bytes)
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);

$message = "Hello secure world";

// Encrypt
$ciphertext = sodium_crypto_secretbox($message, $nonce, $key);

// Store or transmit: nonce + ciphertext (key is kept secret)
$stored = base64_encode($nonce . $ciphertext);

// -------------------

// Decode and split
$decoded = base64_decode($stored, true);

$nonce = substr($decoded, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$ciphertext = substr($decoded, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);

// Decrypt
$decrypted = sodium_crypto_secretbox_open($ciphertext, $nonce, $key);

if ($decrypted === false) {
    die("Decryption failed (message tampered or invalid key)");
}

echo $decrypted;

?>
----
Server IP: 2a03:b0c0:2:f0:0:1:a983:a001 (proxied: BunnyCDN)
Probable Submitter: 49.36.91.224
----
Manual Page -- https://php.net/manual/en/function.sodium-crypto-secretbox.php
Edit        -- https://main.php.net/note/edit/130817
Del: integrated  -- https://main.php.net/note/delete/130817/integrated
Del: useless     -- https://main.php.net/note/delete/130817/useless
Del: bad code    -- https://main.php.net/note/delete/130817/bad+code
Del: spam        -- https://main.php.net/note/delete/130817/spam
Del: non-english -- https://main.php.net/note/delete/130817/non-english
Del: in docs     -- https://main.php.net/note/delete/130817/in+docs
Del: other reasons-- https://main.php.net/note/delete/130817
Reject      -- https://main.php.net/note/reject/130817
Search      -- https://main.php.net/manage/user-notes.php