Skip to content

Instantly share code, notes, and snippets.

@tlikai
Forked from yuriy-yarvinen/encrypt_decrypt.php
Last active November 11, 2021 15:29
Show Gist options
  • Save tlikai/1437e249d8d6a52449e0bc52a2499cc3 to your computer and use it in GitHub Desktop.
Save tlikai/1437e249d8d6a52449e0bc52a2499cc3 to your computer and use it in GitHub Desktop.
php aes-128-cbc
<?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