Files
duckbrain-toolbox/packages/crypto/src/Libs/Crypto.php
T

117 lines
2.8 KiB
PHP

<?php
namespace Libs;
/**
* Crypto - DuckBrain
*
* Class created for encrypting/decrypting
* using openssl with the AES 256 CBC algorithm.
*
* Optionally depends on the PRIVATE_KEY constant.
*
* @author KJ
* @website https://kj2.me
* @license MIT
*/
class Crypto
{
/**
* Encrypts using openssl with the AES 256 CBC algorithm
* and returns the result in hexadecimal.
*
* @param string $data
* @param string $password
*
* @return string
*/
public static function encryptHex(string $data, string $password = PRIVATE_KEY): string
{
return bin2hex(static::encrypt($data, $password));
}
/**
* Decrypts a string from hexadecimal
* and then using openssl with the AES 256 CBC algorithm.
*
* @param string $data Hexadecimal string
* @param string $password
*
* @return string
*/
public static function decryptHex(string $data, string $password = PRIVATE_KEY): string
{
if ($data === '' || !ctype_xdigit($data) || strlen($data) % 2 !== 0) {
return '';
}
return static::decrypt(hex2bin($data), $password);
}
/**
* Encrypts using openssl with the AES 256 CBC algorithm
* and returns the result in base64.
*
* @param string $data
* @param string $password
*
* @return string
*/
public static function encrypt64(string $data, string $password = PRIVATE_KEY): string
{
return base64_encode(static::encrypt($data, $password));
}
/**
* Decrypts a string from base64
* and then using openssl with the AES 256 CBC algorithm.
*
* @param string $data
* @param string $password
*
* @return string
*/
public static function decrypt64(string $data, string $password = PRIVATE_KEY): string
{
return static::decrypt(base64_decode($data), $password);
}
/**
* Encrypts using openssl with the AES 256 CBC algorithm.
*
* @param string $data
* @param string $password
*
* @return string
*/
public static function encrypt(string $data, string $password = PRIVATE_KEY): string
{
return openssl_encrypt(
$data,
'AES-256-CBC',
$password,
OPENSSL_RAW_DATA,
substr($password, 0, 16)
);
}
/**
* Decrypts using openssl with the AES 256 CBC algorithm.
*
* @param string $data
* @param string $password
*
* @return string
*/
public static function decrypt(string $data, string $password = PRIVATE_KEY): string
{
return openssl_decrypt(
$data,
'AES-256-CBC',
$password,
OPENSSL_RAW_DATA,
substr($password, 0, 16)
);
}
}