2012-09-06 110 views
2

我想用php加密數據並插入到mysql中。加密和插入操作正常工作,但解密不會返回實際的字符串。請參閱我下面的代碼進行加密PHP數據加密和解密

public function encryptText($text,$customer_id) 
    { 
     $key = $customer_id; 
     $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB); 
     return $crypttext; 
    } 

對於解密

public function decryptText($ctext,$customer_id) 
    { 
      $key = $customer_id; 
      $text = mcrypt_decrypt(MCRYPT_RIJNDAEL_256,$key,$ctext,MCRYPT_MODE_ECB); 
      return $text; 
    } 

請幫我解決這個問題

+1

*「正常工作,但解密不會返回實際的字符串」* - Sooo,它*不*工作正常呢? ; P – deceze

+1

通常用db來加密數據,如果壞人有權訪問數據庫,他們可能有權訪問用於加密數據的代碼。 – 2012-09-06 10:40:54

+0

你可以發佈你的「測試」代碼嗎?因爲你的代碼的工作原理應該如此。我想,有一些問題,字符串填充或$ customer_id(鍵)參數鑄造。 – Salaros

回答

0

這些功能將採取任何PHP對象和加密/解密他們:

加密JSON對象Rijndael ECB base 64編碼

function ejor2eb($object, $key) { 
    // Encode the object 
    $object = json_encode($object, JSON_FORCE_OBJECT); 

    // Add length onto the encoded object so we can remove the excess padding added by AES 
    $object = strlen($object) . ':' . $object; 

    // Encrypt the string 
    $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND); 
    $result = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $object, MCRYPT_MODE_ECB, $iv); 

    // Return the URL encoded string, with the encryption type attached 
    return 'jor2eu:' . base64_encode($result); 
} 

解密JSON對象的Rijndael ECB基地64解碼

function djor2eb($string, $key, $default = false) { 
    // Remove the encryption type, and decode the string 
    $binary = base64_decode(substr($string, 7)); 
    if (!$binary) { 
     return $default; 
    } 

    // Decrypt the string 
    $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND); 
    $result = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $binary, MCRYPT_MODE_ECB, $iv); 

    // Remove encrption padding 
    $tokens = null; 
    preg_match('/^([0-9]+):/i', $result, $tokens); 
    if (sizeof($tokens) !== 2) { 
     return $default; 
    } 
    $result = substr($result, strlen($tokens[1]) + 1, $tokens[1]); 

    // Decode the ecoded object 
    $object = json_decode($result); 

    return $object; 
} 
1

最有可能的問題是,你沒有使用正確的密鑰來解密加密的數據。您的代碼顯示了很多真的考慮的問題:

  • 的關鍵應該理想地二進制字符串。 $customer_id的確切內容是什麼?即使這是一個字符串,它也應該是128,192或256位長。它看起來不像。
  • 即使密鑰在技術上是可以接受的,但將客戶ID用作密鑰並不能真正提供任何安全性。
  • MCRYPT_RIJNDAEL_256中的256不指定加密強度,但塊大小爲。在幾乎所有情況下,您應該使用MCRYPT_RIJNDAEL_128而不是 - 實際上,這與AES相同。 MCRYPT_RIJNDAEL_256不是AES。
+0

我已經使用customer_id(整數)作爲鍵。 – Vinay

+0

@Vinay:這是行不通的。請花點時間熟悉一下基本的加密文獻,這個錯誤是如此重要,以至於我不能給出比這更好的建議。即使它確實有效,你的系統也不會比以前更安全。加密是你必須正確做的事情,否則它不起作用。 – Jon