2014-09-29 23 views
0

我實現基於一個例子的可逆加密算法存儲在http://www.edzynda.com/create-a-self-destructing-encrypted-message-app-in-laravel-part-1/錯誤試圖加密的字符串中Laravel

我已經把代碼模型事件函數內部:

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,或者什麼都不是,我想不是隨機出現在結果中的字符。

+1

請對您的字符串執行'mb_detect_encoding()',然後退出(),結果如何 – Ohgodwhy 2014-09-29 16:52:11

+0

@Ohgodwhy更新了有問題的信息,謝謝。 – Adamski 2014-09-29 20:11:54

回答

0

我的解決方案:對於存儲和運輸,加密的字符串和IV需要base64編碼。

上面的相關的行改變爲:

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

當然BASE64_DECODE的並且必須解密與存儲的IV值的串之前使用。