Home > Blockchain >  Codeigniter 4: How to detect "Decrypting: authentication failed"
Codeigniter 4: How to detect "Decrypting: authentication failed"

Time:11-01

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:

  1. Get the encrypted string
  2. Decrypt the string: if the decryption succed then proceed with the script, otherwise give a 404 error

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.

CodePudding user response:

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.

CodePudding user response:

Just for the record, here is the complete code to use in Codeigniter 4.

public function testEncryption()
{
    $enc = \Config\Services::encrypter();
    
    $encrypted_string = "9c68ef9159...";
    
    try
    {
        // print the encrypted string
        echo $enc->decrypt(hex2bin($encrypted_string));
    }
    catch(\Exception $e)
    {
        // or if encrypted_string is not valid then show 404 page or do whatever you want
        return view('errors/html/error_404');
    }
}
  • Related