From a43a09a0e275c9c61352426971bb9418bf824c64 Mon Sep 17 00:00:00 2001 From: Uwe Steinmann Date: Tue, 18 Apr 2023 20:09:03 +0200 Subject: [PATCH] use openssl to encrypt and decrypt data with key --- inc/inc.Utils.php | 52 ++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 42 insertions(+), 10 deletions(-) diff --git a/inc/inc.Utils.php b/inc/inc.Utils.php index 444cded70..8c4534a1e 100644 --- a/inc/inc.Utils.php +++ b/inc/inc.Utils.php @@ -582,11 +582,28 @@ function checkQuota($user) { /* {{{ */ * @return string encrypted data */ function encryptData($key, $value) { /* {{{ */ - $text = $value; - $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB); - $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND); - $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB, $iv); - return $crypttext; + if(function_exists('openssl_cipher_iv_length')) { + $nonceSize = openssl_cipher_iv_length('aes-256-ctr'); + $nonce = openssl_random_pseudo_bytes($nonceSize); + + $ciphertext = openssl_encrypt( + $value, + 'aes-256-ctr', + $key, + OPENSSL_RAW_DATA, + $nonce + ); + + // Now let's pack the IV and the ciphertext together + // Naively, we can just concatenate + return $nonce.$ciphertext; + } else { + $text = $value; + $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB); + $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND); + $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB, $iv); + return $crypttext; + } } /* }}} */ /** @@ -597,11 +614,26 @@ function encryptData($key, $value) { /* {{{ */ * @return string plain text data */ function decryptData($key, $value) { /* {{{ */ - $crypttext = $value; - $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB); - $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND); - $decrypttext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $crypttext, MCRYPT_MODE_ECB, $iv); - return trim($decrypttext); + if(function_exists('openssl_cipher_iv_length')) { + $nonceSize = openssl_cipher_iv_length('aes-256-ctr'); + $nonce = mb_substr($value, 0, $nonceSize, '8bit'); + $ciphertext = mb_substr($value, $nonceSize, null, '8bit'); + + $plaintext = openssl_decrypt( + $ciphertext, + 'aes-256-ctr', + $key, + OPENSSL_RAW_DATA, + $nonce + ); + return $plaintext; + } else { + $crypttext = $value; + $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB); + $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND); + $decrypttext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $crypttext, MCRYPT_MODE_ECB, $iv); + return trim($decrypttext); + } } /* }}} */ /**