Skip to content

Instantly share code, notes, and snippets.

@boy3vil
Created February 20, 2014 10:01
Show Gist options
  • Save boy3vil/9110356 to your computer and use it in GitHub Desktop.
Save boy3vil/9110356 to your computer and use it in GitHub Desktop.
<?php // base64_encode()/base64_decode() example
$key = 'password to (en/de)crypt';
$string = ' string to be encrypted '; // note the spaces
$iv = mcrypt_create_iv(
mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC),
MCRYPT_DEV_URANDOM
);
$encrypted = base64_encode(
$iv .
mcrypt_encrypt(
MCRYPT_RIJNDAEL_256,
hash('sha256', $key, true),
$string,
MCRYPT_MODE_CBC,
$iv
)
);
$data = base64_decode($encrypted);
$iv = substr($data, 0, mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC));
$decrypted = rtrim(
mcrypt_decrypt(
MCRYPT_RIJNDAEL_256,
hash('sha256', $key, true),
substr($data, mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC)),
MCRYPT_MODE_CBC,
$iv
),
"\0"
);
echo 'Encrypted:' . "<br/>";
echo $encrypted . "<br/>". "<br/>";// "ey7zu5zBqJB0rGtIn5UB1xG03efyCp+KSNR4/GAv14w="
echo "\n";
echo 'Decrypted:' . "<br/>";
echo $decrypted; // " string to be encrypted "
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment