-
-
Save tlikai/1437e249d8d6a52449e0bc52a2499cc3 to your computer and use it in GitHub Desktop.
php aes-128-cbc
This file contains 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 | |
define('ENCRYPTION_KEY', 'EncryptDecryptPHP201908Y'); | |
// Encrypt | |
function encrypt($plaintext) { | |
$ivlen = openssl_cipher_iv_length($cipher = "AES-128-CBC"); | |
$iv = openssl_random_pseudo_bytes($ivlen); | |
$ciphertext_raw = openssl_encrypt($plaintext, $cipher, ENCRYPTION_KEY, $options = OPENSSL_RAW_DATA, $iv); | |
$hmac = hash_hmac('sha256', $ciphertext_raw, ENCRYPTION_KEY, $as_binary = true); | |
$ciphertext = base64_encode($iv . $hmac . $ciphertext_raw); | |
return $ciphertext; | |
} | |
// Decrypt | |
function decrypt($ciphertext) { | |
$c = base64_decode($ciphertext); | |
$ivlen = openssl_cipher_iv_length($cipher = "AES-128-CBC"); | |
$iv = substr($c, 0, $ivlen); | |
$hmac = substr($c, $ivlen, $sha2len = 32); | |
$ciphertext_raw = substr($c, $ivlen + $sha2len); | |
$plaintext = openssl_decrypt($ciphertext_raw, $cipher, ENCRYPTION_KEY, $options = OPENSSL_RAW_DATA, $iv); | |
$calcmac = hash_hmac('sha256', $ciphertext_raw, ENCRYPTION_KEY, $as_binary = true); | |
if (hash_equals($hmac, $calcmac)) { | |
return $plaintext; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment