43 lines
1.3 KiB
PHP
Executable File
43 lines
1.3 KiB
PHP
Executable File
<?php
|
|
|
|
namespace App\Helpers;
|
|
|
|
/**
|
|
* SysCMS - Encryption Helper
|
|
*
|
|
* Simple AES-256-CBC encryption for sensitive data like API Keys.
|
|
*/
|
|
class Crypto
|
|
{
|
|
private static $cipher = "AES-256-CBC";
|
|
|
|
/**
|
|
* Encrypts a string using the APP_KEY as secret
|
|
*/
|
|
public static function encrypt(string $data): string
|
|
{
|
|
$key = substr(hash('sha256', env('APP_KEY', 'syscms-default-key')), 0, 32);
|
|
$ivlen = openssl_cipher_iv_length(self::$cipher);
|
|
$iv = openssl_random_pseudo_bytes($ivlen);
|
|
$ciphertext = openssl_encrypt($data, self::$cipher, $key, $options = 0, $iv);
|
|
return base64_encode($iv . $ciphertext);
|
|
}
|
|
|
|
/**
|
|
* Decrypts a string
|
|
*/
|
|
public static function decrypt(string $data): string
|
|
{
|
|
try {
|
|
$key = substr(hash('sha256', env('APP_KEY', 'syscms-default-key')), 0, 32);
|
|
$decoded = base64_decode($data);
|
|
$ivlen = openssl_cipher_iv_length(self::$cipher);
|
|
$iv = substr($decoded, 0, $ivlen);
|
|
$ciphertext = substr($decoded, $ivlen);
|
|
return openssl_decrypt($ciphertext, self::$cipher, $key, $options = 0, $iv);
|
|
} catch (\Exception $e) {
|
|
return $data; // Return original if decryption fails (e.g. not encrypted yet)
|
|
}
|
|
}
|
|
}
|