ppowell777's post in How to use libsodium encryption/decryption in PHP 8.3+ and IIS 10+ was marked as the answer
6 hours ago
Solved it; I used too old of a version of encryption/decryption, and the solution was simpler than I thought:
<?php
/**
* Using most recent versions of PHP Sodium functions for PHP 8.3.8. Remember to do the following when requiring this file:
*
* <b>
* require('./globals/constants.php');
* require('./globals/functions.php');
* require('./globals/crypto.php');
* </b>
*/
function decrypt($encText, $nonce, $key) {
try {
if (empty($encText) || empty($nonce) || empty($key)) {
throw new Exception('You must provide text, a nonce, and a key');
}
return sodium_crypto_secretbox_open($encText, $nonce, $key);
} catch (Exception $e) {
$msg = ERROR_MESSAGE . ' hasSecCode() ' . date('Y-m-d H:i:s') . ' ' . $e->getMessage();
toLogDB($msg);
error_log($msg, 0);
throw $e;
}
}
function encrypt($text, $nonce, $key) {
try {
if (empty($text) || empty($nonce) || empty($key)) {
throw new Exception('You must provide text, a nonce, and a key');
}
return sodium_crypto_secretbox($text, $nonce, $key);
} catch (Exception $e) {
$msg = ERROR_MESSAGE . ' hasSecCode() ' . date('Y-m-d H:i:s') . ' ' . $e->getMessage();
toLogDB($msg);
error_log($msg, 0);
throw $e;
}
}
/**
* Wrapper for {@see sodium_crypto_secretbox_keygen}
*/
function getKey() {
try {
return sodium_crypto_secretbox_keygen();
} catch (Exception $e) {
$msg = ERROR_MESSAGE . ' hasSecCode() ' . date('Y-m-d H:i:s') . ' ' . $e->getMessage();
toLogDB($msg);
error_log($msg, 0);
throw $e;
}
}
/**
* Wrapper for {@see random_bytes}
*/
function getNonce() {
try {
return random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
} catch (Exception $e) {
$msg = ERROR_MESSAGE . ' hasSecCode() ' . date('Y-m-d H:i:s') . ' ' . $e->getMessage();
toLogDB($msg);
error_log($msg, 0);
throw $e;
}
}
?>
<?php
require('./globals/constants.php');
require('./globals/functions.php');
require('./globals/crypto.php');
$key = getKey();
$str = 'Lorem ipsum dolor sit amet. The quick brown fox jumped over the lazy dog. Lorem ipsum dolor sit amet';
$nonce = getNonce();
$encStr = encrypt($str, $nonce, $key);
$decStr = decrypt($encStr, $nonce, $key);
if ($decStr === false) {
echo ' was not decrypted<br />';
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Blah</title>
</head>
<body>
<p>
Original string: <?php echo $str ?><br /><br />
Encrypted string: <?php echo $encStr ?><br /><br />
Decrypted string: <?php echo $decStr ?><br /><br />
</p>
</body>
</html>