<?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
Create a free account and build your private vault. Share publicly whenever you want.