Created
October 20, 2023 00:05
-
-
Save jvahldick/399d5732a0e36053ee63d788f73b1e37 to your computer and use it in GitHub Desktop.
AES Encryption/Decryption in PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
final class AESEncrypt | |
{ | |
private const CYPHER_ALGO = 'AES-256-CBC'; | |
public function __construct(private readonly string $passPhrase) | |
{ | |
} | |
public function encrypt(string $plainText): string | |
{ | |
$ivSize = openssl_cipher_iv_length(self::CYPHER_ALGO); | |
$iv = openssl_random_pseudo_bytes($ivSize); | |
$cipherText = openssl_encrypt($plainText, self::CYPHER_ALGO, $this->passPhrase, OPENSSL_RAW_DATA, $iv); | |
return base64_encode($iv . $cipherText); | |
} | |
public function decrypt(string $encryptedText): string | |
{ | |
$data = base64_decode($encryptedText); | |
$ivSize = openssl_cipher_iv_length(self::CYPHER_ALGO); | |
$iv = mb_substr($data, 0, $ivSize, '8bit'); | |
$cipherText = mb_substr($data, $ivSize, null, '8bit'); | |
return openssl_decrypt($cipherText, self::CYPHER_ALGO, $this->passPhrase, OPENSSL_RAW_DATA, $iv); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment