PHP

Encrypt / Decrypt with libsodium

admin by @admin ADMIN
Jun 17, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Symmetric AEAD encryption using the libsodium "secretbox" (XSalsa20-Poly1305). Built into PHP since 7.2 — no extension needed. Returns base64 ciphertext with the nonce prepended.
PHP
Raw
<?php
function encryptSecret(string $plaintext, string $key32): string {
    if (strlen($key32) !== SODIUM_CRYPTO_SECRETBOX_KEYBYTES) {
        throw new InvalidArgumentException('Key must be 32 bytes');
    }
    $nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
    $ct    = sodium_crypto_secretbox($plaintext, $nonce, $key32);
    return base64_encode($nonce . $ct);
}

function decryptSecret(string $b64, string $key32): string|false {
    $raw   = base64_decode($b64, true);
    if ($raw === false) return false;
    $nonce = substr($raw, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
    $ct    = substr($raw, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
    return sodium_crypto_secretbox_open($ct, $nonce, $key32);
}

$key = sodium_crypto_secretbox_keygen();   // 32 random bytes
$cipher = encryptSecret('hello world', $key);
echo decryptSecret($cipher, $key);          // hello world
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.