| 1 |
<?php |
| 2 |
|
| 3 |
namespace BitCode\BitForm\Core\Cryptography; |
| 4 |
|
| 5 |
class Cryptography |
| 6 |
{ |
| 7 |
public static $sodiumCompat; |
| 8 |
|
| 9 |
public static function getSodiumCompat() |
| 10 |
{ |
| 11 |
if (!self::$sodiumCompat) { |
| 12 |
self::$sodiumCompat = new SodiumCompat(); |
| 13 |
} |
| 14 |
return self::$sodiumCompat; |
| 15 |
} |
| 16 |
|
| 17 |
public static function encrypt($message, $key) |
| 18 |
{ |
| 19 |
try { |
| 20 |
if (32 !== strlen($key)) { |
| 21 |
$key = hash('sha256', $key, true); // Generate a 32-byte raw binary key |
| 22 |
} |
| 23 |
return base64_encode(self::getSodiumCompat()->compatEncrypt($message, $key)); |
| 24 |
} catch (Exception $e) { |
| 25 |
// Handle the exception (e.g., log it, rethrow it, or return a meaningful error message) |
| 26 |
error_log('Encryption failed: ' . $e->getMessage()); |
| 27 |
return null; // Or throw new Exception('Encryption failed'); |
| 28 |
} |
| 29 |
} |
| 30 |
|
| 31 |
public static function decrypt($message, $key) |
| 32 |
{ |
| 33 |
try { |
| 34 |
if (32 !== strlen($key)) { |
| 35 |
$key = hash('sha256', $key, true); // Generate a 32-byte raw binary key |
| 36 |
} |
| 37 |
return self::getSodiumCompat()->compatDecrypt(base64_decode($message), $key); |
| 38 |
} catch (Exception $e) { |
| 39 |
// Handle the exception |
| 40 |
error_log('Decryption failed: ' . $e->getMessage()); |
| 41 |
return null; // Or throw new Exception('Decryption failed'); |
| 42 |
} |
| 43 |
} |
| 44 |
} |
| 45 |
|