【问题标题】:Error trying to store encrypted string in Laravel尝试在 Laravel 中存储加密字符串时出错
【发布时间】:2014-11-24 03:23:38
【问题描述】:

我正在根据http://www.edzynda.com/create-a-self-destructing-encrypted-message-app-in-laravel-part-1/ 的示例实现可逆加密算法

我已将代码放入模型事件函数中:

public static function boot()
{
    parent::boot();

    // Setup event bindings...

    static::creating(function($account)
    {
        /* encrypt password and save iv */
        $encryption = self::encrypt($account->db_password);  // or: Input::get('db_password')
        $account->db_password = $encryption['encrypted_string'];
        $account->iv = $encryption['iv'];

        Log::debug($account);

        //print_r ($encryption);

    });


}

public static function encrypt($string) 
{
    // Generate an IV
    $iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_CFB);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_DEV_URANDOM);


    // Encrypt the string
    $encrypted_string = mcrypt_encrypt(MCRYPT_BLOWFISH, $_ENV['ACCOUNT_KEY'], $string, MCRYPT_MODE_CFB, $iv);

    return ['encrypted_string' => $encrypted_string, 'iv' => $iv];
}

在我的数据库播种器中,我调用 Model::create 以使字符串在保存之前被加密。这是从我的测试中调用的。但是,我得到了

  [ErrorException]
  json_encode(): Invalid UTF-8 sequence in argument

我已经确定列类型是二进制的。

额外信息:当我对任一值($iv 或 $string)执行 mb_detect_encoding 时,我得到 UTF-8 或什么都没有,我猜这取决于结果中出现的随机字符。

【问题讨论】:

  • 请先对你的字符串执行mb_detect_encoding(),然后再执行exit(),结果如何
  • @Ohgodwhy 更新了相关信息,谢谢。

标签: php encryption laravel utf-8 mcrypt


【解决方案1】:

我的解决方案:为了存储和运输,加密后的字符串和IV需要进行base64编码。

上面的相关行改为:

return [
            'encrypted_string' => base64_encode($encrypted_string), 
            'iv' => base64_encode($iv)
        ];

在使用存储的 IV 值解密字符串之前,当然必须使用 base64_decode。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-14
    • 2012-05-10
    • 2015-08-03
    • 1970-01-01
    相关资源
    最近更新 更多