How to encrypt / decrypt AES with Libsodium-PHP
Much like the other PHP encryption libraries I have researched Libsoduim-PHP seemed to offer almost no documentation of how to use the library (that I was able to find).
From the libsodium-php Github page you will find a direct link to a free online book that covers everything you need to know to get started with libsodium.
The final chapter contains libsodium recipes, but each chapter contains detailed usage information.
If you specifically need AES, read this.
If you don't have an "AES-or-bust" requirement hanging over your head, where failure to specifically use AES means your department gets axed and your developers face a firing squad, you should consider just using crypto_secretbox which uses Xsalsa20 for encryption and attaches a Poly1305 authentication tag. (This is authenticated encryption, which you want to use almost always.)
Also look into Halite if you want easy-mode.
PHP Version >= 7.2
If you are using PHP >= 7.2 use inbuilt sodium core extension instead.
Sample implementation
<?php
//Simple Usage
/**
* Encrypt a message
*
* @param string $message - message to encrypt
* @param string $key - encryption key
* @return string
*/
function safeEncrypt($message, $key)
{
$nonce = random_bytes(
SODIUM_CRYPTO_SECRETBOX_NONCEBYTES
);
$cipher = base64_encode(
$nonce.
sodium_crypto_secretbox(
$message,
$nonce,
$key
)
);
sodium_memzero($message);
sodium_memzero($key);
return $cipher;
}
/**
* Decrypt a message
*
* @param string $encrypted - message encrypted with safeEncrypt()
* @param string $key - encryption key
* @return string
*/
function safeDecrypt($encrypted, $key)
{
$decoded = base64_decode($encrypted);
if ($decoded === false) {
throw new Exception('Scream bloody murder, the encoding failed');
}
if (mb_strlen($decoded, '8bit') < (SODIUM_CRYPTO_SECRETBOX_NONCEBYTES + SODIUM_CRYPTO_SECRETBOX_MACBYTES)) {
throw new Exception('Scream bloody murder, the message was truncated');
}
$nonce = mb_substr($decoded, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, '8bit');
$ciphertext = mb_substr($decoded, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit');
$plain = sodium_crypto_secretbox_open(
$ciphertext,
$nonce,
$key
);
if ($plain === false) {
throw new Exception('the message was tampered with in transit');
}
sodium_memzero($ciphertext);
sodium_memzero($key);
return $plain;
}
//Encrypt & Decrypt your message
$key = random_bytes(SODIUM_CRYPTO_SECRETBOX_KEYBYTES);
$enc = safeEncrypt('Encrypt This String...', $key); //generates random encrypted string (Base64 related)
echo $enc;
echo '<br>';
$dec = safeDecrypt($enc, $key); //decrypts encoded string generated via safeEncrypt function
echo $dec;