mmeyer2k / secretbox
v0.0.0
2025-01-05 09:53 UTC
Requires
- php: ^8.1
- ext-sodium: *
Requires (Dev)
- phpunit/phpunit: ^10.5
This package is auto-updated.
Last update: 2025-02-18 00:58:38 UTC
README
A minimalist libsodium secretbox implementation with key rotation.
install
composer require mmeyer2k/secretbox
usage
use \Mmeyer2k\SecretBox\SecretBox; $key = random_bytes(32); $enc = SecretBox::encrypt('secret message', $key); $dec = SecretBox::decrypt($enc, $key);
keys
create
SecretBox expects keys to be strings with 32 bytes of pseudorandom-ness.
head -c 32 /dev/urandom | base64 -w 0 | xargs echo
store
In code or environment files, it is best to store keys in an encoded format.
$key = base64_decode("[your base64 key]");
rotate
Easily rotate keys by passing allowable decryption keys in an array.
$dec = SecretBox::decrypt($ciphertext, [ 'key 0', 'key 1', 'key 2', ]);
If decryption is successful, the index of the correct key will be passed by reference through the optional index
parameter.
In this example, $index
will equal 0 if the first key was successful
$index = null; $dec = SecretBox::decrypt($ciphertext, $keys, $index);
handle decryption failures
A \SodiumException
will be thrown if decryption failed due to no matching keys.
try { $dec = SecretBox::decrypt($ciphertext, $key); } catch (\SodiumException) { # ... }