Jump to content

How to use libsodium encryption/decryption in PHP 8.3+ and IIS 10+


Go to solution Solved by ppowell777,

Recommended Posts

I am trying to learn how to use encryption and decryption using the built-in libsodium.dll module I have for PHP 8.3.8 and IIS 10+, however, I am unable to get it to work; I am getting this error:

 

Quote

PHP Fatal error: Uncaught Error: Undefined constant "CRYPTO_SECRETBOX_KEYBYTES" in C:\inetpub\wwwroot\pages\blah.php:5 Stack trace: #0 {main} thrown in C:\inetpub\wwwroot\pages\blah.php on line 5

Here is the code:

<?php
// PECL libsodium 0.2.1 and newer

/**
 * Found at <a href="https://stackoverflow.com/questions/3422759/php-aes-encrypt-decrypt">
 * https://stackoverflow.com/questions/3422759/php-aes-encrypt-decrypt</a>
 */

/**
 * Encrypt a message
 * 
 * @param string $message - message to encrypt
 * @param string $key - encryption key
 * @return string
 */
function safeEncrypt($message, $key)
{
    $nonce = \Sodium\randombytes_buf(
        \Sodium\CRYPTO_SECRETBOX_NONCEBYTES
    );

    return base64_encode(
        $nonce.
        \Sodium\crypto_secretbox(
            $message,
            $nonce,
            $key
        )
    );
}

/**
 * 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);
    $nonce = mb_substr($decoded, 0, \Sodium\CRYPTO_SECRETBOX_NONCEBYTES, '8bit');
    $ciphertext = mb_substr($decoded, \Sodium\CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit');

    return \Sodium\crypto_secretbox_open(
        $ciphertext,
        $nonce,
        $key
    );
}   

?>

<?php
	
	require('./globals/crypto.php');
	
	$key = \Sodium\random_bytes(\Sodium\CRYPTO_SECRETBOX_KEYBYTES);
	$str = 'Lorem ipsum dolor sit amet. The quick brown fox jumped over the lazy dog. Lorem ipsum dolor sit amet';
	$encStr = safeEncrypt($str, $key);
	$decStr = safeDecrypt($encStr, $key);

?>
<!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>

What else should I be doing to ensure encryption and decryption works?

Thanks

  • Solution

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>

 

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.