Created
September 15, 2021 22:28
-
-
Save mudssrali/5841a5909e4d6cb241300a3aa82b3d24 to your computer and use it in GitHub Desktop.
PHP implementation of AES encryption and decryption using openssl_encrypt and openssl_decrypt with initialization vector
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 | |
$ENCRYPTION_KEY = "put something secret here"; | |
$ENCRYPTION_ALGORITHM = 'AES-256-CBC'; | |
function encrypt($plain_text) { | |
global $ENCRYPTION_KEY; | |
global $ENCRYPTION_ALGORITHM; | |
$EncryptionKey = make_hash($ENCRYPTION_KEY, 32); | |
// create random Initialization Vector | |
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($ENCRYPTION_ALGORITHM)); | |
$encrypted_text = openssl_encrypt( | |
$plain_text, | |
$ENCRYPTION_ALGORITHM, | |
$EncryptionKey, | |
OPENSSL_RAW_DATA, | |
$iv | |
); | |
# concatenate the IV for decryption | |
return base64_encode($iv . $encrypted_text); | |
} | |
function decrypt($ciphertext) { | |
global $ENCRYPTION_KEY; | |
global $ENCRYPTION_ALGORITHM; | |
$EncryptionKey = make_hash($ENCRYPTION_KEY, 32); | |
$ciphertext = base64_decode($ciphertext); | |
// get Initialization Vector part (16 bytes long) | |
$iv = substr($ciphertext, 0, 16); | |
// rest is actual cipher text | |
$ciphertext = substr($ciphertext, 16); | |
$decrypted_text = openssl_decrypt( | |
$ciphertext, | |
$ENCRYPTION_ALGORITHM, | |
$EncryptionKey, | |
OPENSSL_RAW_DATA, | |
$iv | |
); | |
return $decrypted_text; | |
} | |
function make_hash($text, $length) { | |
$hash_key = hash("sha512", $text, false); | |
return substr($hash_key,0,$length); | |
} | |
// $ct = encrypt("code"); | |
// $dt = decrypt($ct); | |
// echo $ct."\n"; | |
// echo $dt."\n"; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment