Friedrich Hotz
Friedrich Hotz

Reputation: 21

openssl_encrypt gives different results

With the introduction of GDPR it is advisable to start encrypting sensitive data entered in your database. I intended to equip myself with a couple of experiences The doubt is fast enough, changing servers or updating the php to a longer version, the algorithms are copied by php.net and well referenced by many users should they be obsolete and therefore no longer supported? I would find myself with a lot of data on a database without being able to do anything about it. I'm currently using the next code.

When I use the secured_encrypt function several times, I get different results every time. How is it possible?

Thank you!

    <?php

public function secured_encrypt($data){
$first_key = base64_decode($this -> FIRSTKEY);
$second_key = base64_decode($this -> SECONDKEY);   

$method = "aes-256-cbc";   
$iv_length = openssl_cipher_iv_length($method);
$iv = openssl_random_pseudo_bytes($iv_length);

$first_encrypted = openssl_encrypt($data, $method,$first_key, OPENSSL_RAW_DATA ,$iv);   
$second_encrypted = hash_hmac('sha3-512', $first_encrypted, $second_key, TRUE);

$output = base64_encode($iv.$second_encrypted.$first_encrypted);   
return $output;       
}


public function secured_decrypt($input){
$first_key = base64_decode($this -> FIRSTKEY);
$second_key = base64_decode($this -> SECONDKEY);           
$mix = base64_decode($input);

$method = "aes-256-cbc";   
$iv_length = openssl_cipher_iv_length($method);

$iv = substr($mix,0,$iv_length);
$second_encrypted = substr($mix,$iv_length,64);
$first_encrypted = substr($mix,$iv_length+64);

$data = openssl_decrypt($first_encrypted,$method, $first_key,OPENSSL_RAW_DATA, $iv);
$second_encrypted_new = hash_hmac('sha3-512', $first_encrypted, $second_key, TRUE);

if (hash_equals($second_encrypted,$second_encrypted_new))
return $data;

return false;
}  
?>

Upvotes: 2

Views: 940

Answers (1)

WoLfulus
WoLfulus

Reputation: 1967

You're setting the initialization vector with openssl_random_pseudo_bytes

Upvotes: 1

Related Questions