<?php
$string = "secret";
function getKey($seed='no seed??') {
return hash('sha256', $seed, 1);
}
function encrypt($key, $string) {
$size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($size, MCRYPT_RAND);
$encrypted_string = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $string, MCRYPT_MODE_CBC, $iv);
return base64_encode($iv . $encrypted_string);
}
function decrypt($key, $encoded_string) {
$binary = base64_decode($encoded_string);
$size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
$iv = substr($binary, 0, $size);
$encrypted_string = substr($binary, $size);
return mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $encrypted_string, MCRYPT_MODE_CBC, $iv);
}
$key = getKey('Some Secret String');
$encrypted = encrypt($key, 'This is a string that will be encrypted');
echo decrypt($key, $encrypted);
preferences:
50.16 ms | 402 KiB | 5 Q