initial commit
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone Build is passing

This commit is contained in:
2024-02-16 15:44:24 -06:00
commit 19849f3752
8 changed files with 350 additions and 0 deletions

70
src/DataEncryptor.php Normal file
View File

@@ -0,0 +1,70 @@
<?php
namespace Hpz937\Encryption;
/**
* Class DataEncryptor provides methods to encrypt and decrypt data using OpenSSL with AES-256-CBC encryption.
*/
class DataEncryptor {
/**
* @var string The encryption method to use.
*/
private $encryptMethod = "AES-256-CBC";
/**
* @var string The secret key for encryption and decryption.
*/
private $secretKey;
/**
* Constructs the DataEncryptor object with a secret key.
*
* @param string $key The secret key used for encryption and decryption. It is recommended to be a strong, unique key.
*/
public function __construct(string $key)
{
$this->secretKey = hash('sha256', $key);
}
/**
* Encrypts the given data using AES-256-CBC encryption and returns the base64 encoded encrypted data with the IV prepended.
*
* @param string $data The plaintext data to encrypt.
* @return string The base64 encoded encrypted data with the IV prepended.
*/
public function encrypt($data)
{
// Generate a unique IV for each encryption
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($this->encryptMethod));
// Encrypt the data
$encryptedData = openssl_encrypt($data, $this->encryptMethod, $this->secretKey, 0, $iv);
// Prepend the IV to the encrypted data for storage
$encryptedDataWithIv = base64_encode($iv . $encryptedData);
return $encryptedDataWithIv;
}
/**
* Decrypts the given data, which includes the IV and the encrypted data, using AES-256-CBC decryption.
*
* @param string $dataWithIv The base64 encoded encrypted data with the IV prepended.
* @return string The decrypted plaintext data.
*/
public function decrypt($dataWithIv)
{
// Decode from base64
$dataWithIv = base64_decode($dataWithIv);
// Extract the IV and encrypted data
$ivLength = openssl_cipher_iv_length($this->encryptMethod);
$iv = substr($dataWithIv, 0, $ivLength);
$encryptedData = substr($dataWithIv, $ivLength);
// Decrypt the data
$decryptedData = openssl_decrypt($encryptedData, $this->encryptMethod, $this->secretKey, 0, $iv);
return $decryptedData;
}
}