Skip to content

Instantly share code, notes, and snippets.

@alexc-hollywood
Created May 25, 2023 22:44
Show Gist options
  • Save alexc-hollywood/279eb739ded9609a586680113647b883 to your computer and use it in GitHub Desktop.
Save alexc-hollywood/279eb739ded9609a586680113647b883 to your computer and use it in GitHub Desktop.
Encrypt/decrypt with libsodium
<?php
function encrypt (string $message, string $key) : array
{
$nonce = random_bytes (SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$ciphertext = sodium_crypto_secretbox ($message, $nonce, base64_decode ($key));
return [
'nonce' => base64_encode ($nonce),
'ciphertext' => base64_encode ($ciphertext)
];
}
function decrypt (string $ciphertext, string $nonce, string $key) : string
{
return sodium_crypto_secretbox_open ($ciphertext, base64_decode ($nonce), base64_decode ($key));
}
$message = "this is a string to be encrypted with libsodium.";
$key = base64_encode (sodium_crypto_secretbox_keygen());
var_dump ($key);
$payload = encrypt ($message, $key);
var_dump ($payload);
var_dump (decrypt ($payload['ciphertext'], $payload['nonce'], $key));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment