From 3fda1bef6008030116a7ad5d99d545517ac9795e Mon Sep 17 00:00:00 2001 From: Clemens Schwaighofer Date: Wed, 27 Mar 2024 11:58:53 +0900 Subject: [PATCH] Move Symmetric Encryption Key generation into its own method Test update for future class based encryption system without static methods --- www/admin/class_test.encryption.php | 7 ++++ .../CoreLibs/Security/SymmetricEncryption.php | 32 ++++++++++++------- 2 files changed, 27 insertions(+), 12 deletions(-) diff --git a/www/admin/class_test.encryption.php b/www/admin/class_test.encryption.php index c03e5515..523aeb55 100644 --- a/www/admin/class_test.encryption.php +++ b/www/admin/class_test.encryption.php @@ -92,6 +92,13 @@ try { print "Error: " . $e->getMessage() . "
"; } +// echo "
"; +// $key = CreateKey::generateRandomKey(); +// $se = new SymmetricEncryption($key); +// $string = "I a some deep secret"; +// $encrypted = $se->encrypt($string); +// $decrypted = $se->decrypt($encrypted); + print ""; // __END__ diff --git a/www/lib/CoreLibs/Security/SymmetricEncryption.php b/www/lib/CoreLibs/Security/SymmetricEncryption.php index 2586e94a..8062fb51 100644 --- a/www/lib/CoreLibs/Security/SymmetricEncryption.php +++ b/www/lib/CoreLibs/Security/SymmetricEncryption.php @@ -22,15 +22,12 @@ use SodiumException; class SymmetricEncryption { /** - * Encrypt a message + * create key and check validity * - * @param string $message Message to encrypt - * @param string $key Encryption key (as hex string) - * @return string - * @throws \Exception - * @throws \RangeException + * @param string $key The key from which the binary key will be created + * @return string Binary key string */ - public static function encrypt(string $message, string $key): string + public static function createKey(string $key): string { try { $key = CreateKey::hex2bin($key); @@ -43,6 +40,21 @@ class SymmetricEncryption . 'SODIUM_CRYPTO_SECRETBOX_KEYBYTES bytes long).' ); } + return $key; + } + + /** + * Encrypt a message + * + * @param string $message Message to encrypt + * @param string $key Encryption key (as hex string) + * @return string + * @throws \Exception + * @throws \RangeException + */ + public static function encrypt(string $message, string $key): string + { + $key = self::createKey($key); $nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES); $cipher = base64_encode( @@ -68,11 +80,7 @@ class SymmetricEncryption */ public static function decrypt(string $encrypted, string $key): string { - try { - $key = CreateKey::hex2bin($key); - } catch (SodiumException $e) { - throw new \Exception('Invalid hex key'); - } + $key = self::createKey($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');