Created
May 25, 2023 22:44
-
-
Save alexc-hollywood/279eb739ded9609a586680113647b883 to your computer and use it in GitHub Desktop.
Encrypt/decrypt with libsodium
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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