I am trying to develop a php program that encrypts some data which can later be decrypted. However, I am having trouble decrypting the data with PHP using AES-256-CBC algorithm by using the openssl_decrypt() method in PHP. The encryption works but when I try to decrypt it gives me an error:-
hash_equals(): Expected known_string to be a string, bool given on line 44.
My code below:
<?php
class Encryption{
protected $data, $encryption_type, $key, $iv;
public function __construct(){
$mydata = "Is this safe";
$encryption = $this->secured_encryption($mydata);
// Decrypting data
$data_to_decrypt = $encryption;
$this->decrypt_data($data_to_decrypt);
}
public function secured_encryption($data){
$this->data = $data;
$this->encryption_type = "AES-256-CBC"; // cipher algorithm
$this->key = ['6d2d823df2e08c0d3cdf70f148998d49', 'fdb3a18c7b0a322fdb3a18c7b0a320d3'];
$this->iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($this->encryption_type));
$encrypted_data = openssl_encrypt($this->data, $this->encryption_type, $this->key[0], OPENSSL_RAW_DATA, $this->iv);
$final_encryption = hash_hmac('SHA3-512', $encrypted_data, $this->key[1], true);
$output = base64_encode($this->iv.$final_encryption.$encrypted_data);
if($output):
print("Encrypted data: {$output}<br/>");
else:
print("Error in encrypting data");
endif;
}
public function decrypt_data($data){
$this->data = base64_decode($data);
$this->encryption_type = "AES-256-CBC"; // cipher algorithm
$this->key = ['6d2d823df2e08c0d3cdf70f148998d49', 'fdb3a18c7b0a322fdb3a18c7b0a320d3'];
$ivlen = openssl_cipher_iv_length($this->encryption_type);
$this->iv = substr($this->data, 0, $ivlen);
$hmac = substr($this->data, $ivlen, $sha2len = 32);
$decrypt_data = substr($this->data, $ivlen, $sha2len);
$final_decryption = openssl_decrypt($decrypt_data, $this->encryption_type, $this->key[0], OPENSSL_RAW_DATA, $this->iv);
$calcmac = hash_hmac('SHA3-512', $decrypt_data, $this->key[1], true);
if(hash_equals($hmac, $calcmac)):
print($final_decryption);
else:
print("Error in decrypting data");
endif;
}
}
$encryption = Encryption();
?>
Anybody to help me