I'm stuck with a problem while using Codeigniter 4 and the encryption service. All works well, I can encrypt and decrypt without any problem but I want to detect when the encrypted string gives the error "Decrypting: authentication failed."
Basically all I'm trying to do is this:
Here is my test code, maybe it helps to explain my problem
$ct1 is the correct encrypted string, $ct2 is the same string but with the first character changed, just to simulate an error, the first is decrypted correctly, the second gives an error, I want to detect this error and show the 404 page (I know how to show the 404 page, I just need a way to detect the error).
$enc = \Config\Services::encrypter();
$ct1 = "9c68ef9159b..."; //The string is very long, I don't think is necessary to write it all
$ct2 = "1c68ef9159b...";
print_r($enc->decrypt(hex2bin($ct1)));
print_r($enc->decrypt(hex2bin($ct2)));
Thanks in advance to everyone willing to help me.
You can make a function for the decrypt like below:
public function decrypt_token($ct1){
try{
$enc->decrypt(hex2bin($ct1))
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
// or
header('Location: http://www.example.com/404');
}
}
For more you can read here.