Created
April 11, 2015 06:02
-
-
Save Amadren/d3e5384c5f9346a21050 to your computer and use it in GitHub Desktop.
AES php encryption sample
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 | |
$password = "myPassword_!"; | |
$messageClear = "Secret message"; | |
// 32 byte binary blob | |
$aes256Key = hash("SHA256", $password, true); | |
// for good entropy (for MCRYPT_RAND) | |
srand((double) microtime() * 1000000); | |
// generate random iv | |
$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC), MCRYPT_RAND); | |
$crypted = fnEncrypt($messageClear, $aes256Key); | |
$newClear = fnDecrypt($crypted, $aes256Key); | |
echo | |
"IV: <code>".$iv."</code><br/>". | |
"Encrypred: <code>".$crypted."</code><br/>". | |
"Decrypred: <code>".$newClear."</code><br/>"; | |
function fnEncrypt($sValue, $sSecretKey) { | |
global $iv; | |
return rtrim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $sSecretKey, $sValue, MCRYPT_MODE_CBC, $iv)), "\0\3"); | |
} | |
function fnDecrypt($sValue, $sSecretKey) { | |
global $iv; | |
return rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $sSecretKey, base64_decode($sValue), MCRYPT_MODE_CBC, $iv), "\0\3"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment