Search the Community
Showing results for tags 'encryption'.
-
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: 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