This is a question related to security posted here.
I am using this in my current PHP 7.0 setup which works fine. But because mcrypt has been replaced with openssl since 7.2, I am working to update the encrypt and decrypt functions with the ones posted here since it's built-in.
But because this is on a webpage with 25 items, it's taking a lot of time to execute which is unacceptable to the end-user.
<?php
define("ENCRYPTION_KEY", "!@#$%^&*");
$StartTime = microtime(TRUE);
$e = [];
for ($i = 0; $i < 25; $i++)
{
$e[] = encrypt($i, ENCRYPTION_KEY);
}
echo number_format(microtime(TRUE) - $StartTime, 3)." seconds\n";
# https://stackoverflow.com/a/50373095/126833
function sign($message, $key) {
return hash_hmac('sha256', $message, $key) . $message;
}
function verify($bundle, $key) {
return hash_equals(
hash_hmac('sha256', mb_substr($bundle, 64, null, '8bit'), $key),
mb_substr($bundle, 0, 64, '8bit')
);
}
function getKey($password, $keysize = 16) {
return hash_pbkdf2('sha256',$password,'some_token',100000,$keysize,true);
}
function encrypt($message, $password) {
$iv = random_bytes(16);
$key = getKey($password);
$result = sign(openssl_encrypt($message,'aes-256-ctr',$key,OPENSSL_RAW_DATA,$iv), $key);
return bin2hex($iv).bin2hex($result);
}
function decrypt($hash, $password) {
$iv = hex2bin(substr($hash, 0, 32));
$data = hex2bin(substr($hash, 32));
$key = getKey($password);
if (!verify($data, $key)) {
return null;
}
return openssl_decrypt(mb_substr($data, 64, null, '8bit'),'aes-256-ctr',$key,OPENSSL_RAW_DATA,$iv);
}
?>
.
$ php encrypt-decrypt.php
6.288 seconds
Is there any way to execute this real fast ? (Like less than a second for 25 iterations)