Move Symmetric Encryption Key generation into its own method

Test update for future class based encryption system without static
methods
This commit is contained in:
Clemens Schwaighofer
2024-03-27 11:58:53 +09:00
parent 4f1104c36e
commit 3fda1bef60
2 changed files with 27 additions and 12 deletions

View File

@@ -92,6 +92,13 @@ try {
print "Error: " . $e->getMessage() . "<br>"; print "Error: " . $e->getMessage() . "<br>";
} }
// echo "<hr>";
// $key = CreateKey::generateRandomKey();
// $se = new SymmetricEncryption($key);
// $string = "I a some deep secret";
// $encrypted = $se->encrypt($string);
// $decrypted = $se->decrypt($encrypted);
print "</body></html>"; print "</body></html>";
// __END__ // __END__

View File

@@ -22,15 +22,12 @@ use SodiumException;
class SymmetricEncryption class SymmetricEncryption
{ {
/** /**
* Encrypt a message * create key and check validity
* *
* @param string $message Message to encrypt * @param string $key The key from which the binary key will be created
* @param string $key Encryption key (as hex string) * @return string Binary key string
* @return string
* @throws \Exception
* @throws \RangeException
*/ */
public static function encrypt(string $message, string $key): string public static function createKey(string $key): string
{ {
try { try {
$key = CreateKey::hex2bin($key); $key = CreateKey::hex2bin($key);
@@ -43,6 +40,21 @@ class SymmetricEncryption
. 'SODIUM_CRYPTO_SECRETBOX_KEYBYTES bytes long).' . '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); $nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$cipher = base64_encode( $cipher = base64_encode(
@@ -68,11 +80,7 @@ class SymmetricEncryption
*/ */
public static function decrypt(string $encrypted, string $key): string public static function decrypt(string $encrypted, string $key): string
{ {
try { $key = self::createKey($key);
$key = CreateKey::hex2bin($key);
} catch (SodiumException $e) {
throw new \Exception('Invalid hex key');
}
$decoded = base64_decode($encrypted); $decoded = base64_decode($encrypted);
$nonce = mb_substr($decoded, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, '8bit'); $nonce = mb_substr($decoded, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, '8bit');
$ciphertext = mb_substr($decoded, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit'); $ciphertext = mb_substr($decoded, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit');