note 130816 added to function.sodium-crypto-secretbox

From: Date: Wed, 10 Jun 2026 12:13:25 +0000
Subject: note 130816 added to function.sodium-crypto-secretbox
Groups: php.notes 
Request: Send a blank email to php-notes+get-222603@lists.php.net to get a copy of this message
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/130816 Del: integrated -- https://main.php.net/note/delete/130816/integrated Del: useless -- https://main.php.net/note/delete/130816/useless Del: bad code -- https://main.php.net/note/delete/130816/bad+code Del: spam -- https://main.php.net/note/delete/130816/spam Del: non-english -- https://main.php.net/note/delete/130816/non-english Del: in docs -- https://main.php.net/note/delete/130816/in+docs Del: other reasons-- https://main.php.net/note/delete/130816 Reject -- https://main.php.net/note/reject/130816 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#222603) next »