Created
January 22, 2020 17:08
-
-
Save drumer2142/b58c0ce60c2e546b9cbc982302ab1de1 to your computer and use it in GitHub Desktop.
Basic PHP Encryption Algorithm
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 | |
$toencrypt = 'The Big Blue House'; | |
$key = 'dGVzdCB0ZXN0IHRlc3QgdGVzdA=='; | |
$cipher = 'AES-128-CBC'; | |
$enc_data = encryptthis($toencrypt, $key, $cipher); | |
var_dump($enc_data); | |
echo "<br>"; | |
decryptthis($enc_data, $key, $cipher); | |
function encryptthis($toencrypt, $key, $cipher){ | |
$ivlen = openssl_cipher_iv_length($cipher); | |
$iv = openssl_random_pseudo_bytes($ivlen); | |
$ciphertext_raw = openssl_encrypt($toencrypt, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv); | |
$hmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary=true); | |
$ciphertext = base64_encode( $iv.$hmac.$ciphertext_raw ); | |
return $ciphertext; | |
} | |
function decryptthis($todecrypt, $key, $cipher){ | |
$c = base64_decode($todecrypt); | |
$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); | |
$original_plaintext = openssl_decrypt($ciphertext_raw, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv); | |
$calcmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary=true); | |
if (hash_equals($hmac, $calcmac))//PHP 5.6+ timing attack safe comparison | |
{ | |
var_dump($original_plaintext."\n"); | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment