From 25d3ce4ee8f411a19c3a0e69ebb5c575c16243a8 Mon Sep 17 00:00:00 2001 From: Andrew Dolgov Date: Tue, 8 Apr 2025 08:55:44 +0300 Subject: drop SESSION-specific stuff and move encrypt/decrypt helpers to a separate class; add a command line flag to generate encryption keys --- classes/Crypt.php | 62 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 classes/Crypt.php (limited to 'classes/Crypt.php') diff --git a/classes/Crypt.php b/classes/Crypt.php new file mode 100644 index 000000000..d832e6530 --- /dev/null +++ b/classes/Crypt.php @@ -0,0 +1,62 @@ + self::ENCRYPT_ALGO, + 'nonce' => $nonce, + 'payload' => $payload, + ]; + + return $encrypted_data; + } + + throw new Exception("Crypt::encrypt_string() failed to encrypt ciphertext"); + } + + /** decrypts payload of a valid encrypted object using Config::ENCRYPTION_KEY + * + * @param array{'algo': string, 'nonce': string, 'payload': string} $encrypted_data + * + * @return string decrypted string payload + */ + static function decrypt_string(array $encrypted_data) : string { + $key = Config::get(Config::ENCRYPTION_KEY); + + if (!$key) + throw new Exception("Crypt::decrypt_string() failed to decrypt - key is not available"); + + // only one is supported for the time being + switch ($encrypted_data['algo']) { + case self::ENCRYPT_ALGO: + return sodium_crypto_aead_xchacha20poly1305_ietf_decrypt($encrypted_data['payload'], '', $encrypted_data['nonce'], hex2bin($key)); + } + + throw new Exception('Crypt::decrypt_string() failed to decrypt passed encrypted data object, unsupported algo: ' . $encrypted_data['algo']); + } + +} \ No newline at end of file -- cgit v1.2.3-54-g00ecf