Last active
October 25, 2018 03:58
-
-
Save thejohn/f54083cb539b48174f55 to your computer and use it in GitHub Desktop.
Simple PHP Encrypt, Decrypt
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
function encrypt($data, $salt='!kQm*fF3pXe1Kbm%9') { | |
$key = hash('SHA256', $salt, true); | |
srand(); $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_RAND); | |
if (strlen($iv_base64 = rtrim(base64_encode($iv), '=')) != 22){ | |
return false; | |
} | |
$encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data . md5($data), MCRYPT_MODE_CBC, $iv)); | |
return $iv_base64 . $encrypted; | |
} | |
function decrypt($cypher, $salt='!kQm*fF3pXe1Kbm%9') { | |
$key = hash('SHA256', $salt, true); | |
$iv = base64_decode(substr($cypher, 0, 22) . '=='); | |
$encrypted = substr($cypher, 22); | |
$decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, base64_decode($encrypted), MCRYPT_MODE_CBC, $iv), "\0\4"); | |
$hash = substr($decrypted, -32); | |
$decrypted = substr($decrypted, 0, -32); | |
if (md5($decrypted) != $hash) return false; | |
return $decrypted; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment