【问题标题】:Codeigniter 4: How to detect "Decrypting: authentication failed"Codeigniter 4:如何检测“解密:身份验证失败”
【发布时间】:2021-12-15 16:39:09
【问题描述】:

我在使用 Codeigniter 4 和加密服务时遇到了问题。 一切正常,我可以毫无问题地加密和解密,但我想检测加密字符串何时给出错误“解密:身份验证失败。”

基本上我要做的就是这样:

  1. 获取加密字符串
  2. 解密字符串:如果解密成功则继续执行脚本,否则给出404错误

这是我的测试代码,也许它有助于解释我的问题

$ct1 是正确的加密字符串,$ct2 是同一个字符串但是第一个字符改变了,只是为了模拟一个错误,第一个被正确解密,第二个给出错误,我想检测这个错误并显示 404 页面(我知道如何显示 404 页面,我只需要一种检测错误的方法。

$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)));

提前感谢所有愿意帮助我的人。

【问题讨论】:

  • 尝试向$enc->decrypt(hex2bin($ct2))添加try-catch

标签: php codeigniter encryption codeigniter-4


【解决方案1】:

您可以为解密创建一个函数,如下所示:

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');
    }
}

更多信息请阅读here

【讨论】:

  • 谢谢,它有帮助。在 Codeigniter 4 中,我们需要在关键字 'Exception' 之前添加字符 '\'。我会尽快发布带有完整代码的答案。
【解决方案2】:

仅作记录,这里是 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');
    }
}

【讨论】:

    猜你喜欢
    • 2014-08-17
    • 2014-12-28
    • 2021-06-19
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 2013-04-22
    • 2019-04-18
    • 2011-06-23
    相关资源
    最近更新 更多