尝试在Laravel中存储加密字符串时出错


Error trying to store encrypted string in Laravel

我正在基于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,要么什么都没有,我想这与结果中出现的随机字符无关。

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

上面的相关行更改为:

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

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