2022-09-19 14:12:03 +02:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Controller;
|
|
|
|
use Exception;
|
|
|
|
use SodiumException;
|
|
|
|
|
|
|
|
/**
|
|
|
|
*
|
|
|
|
*/
|
|
|
|
class EncryptionController
|
|
|
|
{
|
|
|
|
/**
|
|
|
|
* Encrypt a message
|
|
|
|
*
|
|
|
|
* @param string $message - message to encrypt
|
|
|
|
* @param string $key - encryption key
|
|
|
|
* @return string
|
|
|
|
* @throws SodiumException
|
|
|
|
* @throws Exception
|
|
|
|
*/
|
|
|
|
function safeEncrypt(string $message, string $key): string
|
|
|
|
{
|
|
|
|
$nonce = random_bytes(length: SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
|
|
|
|
|
|
|
|
$cipher = base64_encode(string: $nonce . sodium_crypto_secretbox(message: $message, nonce: $nonce, key: $key));
|
|
|
|
sodium_memzero(string: $message);
|
|
|
|
sodium_memzero(string: $key);
|
|
|
|
return $cipher;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Decrypt a message
|
|
|
|
*
|
|
|
|
* @param string $encrypted - message encrypted with safeEncrypt()
|
|
|
|
* @param string $key - encryption key
|
|
|
|
* @return string
|
|
|
|
* @throws SodiumException
|
|
|
|
* @throws Exception
|
|
|
|
*/
|
|
|
|
function safeDecrypt(string $encrypted, string $key): string
|
|
|
|
{
|
2022-09-21 16:01:44 +02:00
|
|
|
$binKey = sodium_hex2bin(string: $key);
|
|
|
|
|
2022-09-19 14:12:03 +02:00
|
|
|
$decoded = base64_decode(string: $encrypted);
|
|
|
|
if ($decoded === false) {
|
2022-09-21 16:01:44 +02:00
|
|
|
throw new Exception(message: 'Decoding broken. Wrong payload.');
|
2022-09-19 14:12:03 +02:00
|
|
|
}
|
2022-09-21 16:01:44 +02:00
|
|
|
|
2022-09-19 14:12:03 +02:00
|
|
|
if (mb_strlen(string: $decoded, encoding: '8bit') < (SODIUM_CRYPTO_SECRETBOX_NONCEBYTES + SODIUM_CRYPTO_SECRETBOX_MACBYTES)) {
|
|
|
|
throw new Exception(message: 'Decoding broken. Incomplete message.');
|
|
|
|
}
|
2022-09-21 16:01:44 +02:00
|
|
|
|
2022-09-19 14:12:03 +02:00
|
|
|
$nonce = mb_substr(string: $decoded, start: 0, length: SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, encoding: '8bit');
|
|
|
|
$ciphertext = mb_substr(string: $decoded, start: SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, length: null, encoding: '8bit');
|
|
|
|
|
2022-09-21 16:01:44 +02:00
|
|
|
$plain = sodium_crypto_secretbox_open(ciphertext: $ciphertext, nonce: $nonce, key: $binKey);
|
2022-09-19 14:12:03 +02:00
|
|
|
if ($plain === false) {
|
|
|
|
throw new Exception(message: 'The message was tampered with in transit');
|
|
|
|
}
|
|
|
|
sodium_memzero(string: $ciphertext);
|
|
|
|
sodium_memzero(string: $key);
|
|
|
|
return $plain;
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|