2011-06-21 189 views
0

加密字符串"1234567890"後,我用hex2bin函數將加密的字符串轉換爲二進制格式並得到"ea359482e4b20603bfe9"php解密加密數據

但我試圖解密回1234567890失敗(總是得到有線字符)。

我錯過了什麼?

下面是一個示例。

<?php 

$text = "1234567890"; 
$key = "TestingKey"; 
echo "SRC: ".$text."<br/>"; 

$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CFB), MCRYPT_RAND); 
$encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_CFB, $iv); 
//$encrypted = bin2hex($encrypted); 
$encrypted = "ea359482e4b20603bfe9"; //this was one of the string that came out. 
echo "ENC: ".$encrypted."<br/>"; 

$encrypted = hex2bin($encrypted); 
$decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $encrypted, MCRYPT_MODE_CFB, $iv); 
echo "DEC: ".$decrypted."<br/>"; 

function hex2bin($text) 
{ 
    $len = strlen($text); 
    for($i=0;$i<$len;$i+=2) 
    { 
     $binary .= pack("C",hexdec(substr($text,$i,2))); 
    } 
    return $binary; 
} 

?>

謝謝!

回答

0

對於這種工作,我通常使用base64_encode和解碼,它與代碼類似於你的代碼。

+0

謝謝Manhim。不幸的是,我必須使用mcrypt_encrypt,因爲我正在處理的項目需要使用這種方法。 – Felasfaw

+0

@Felasfaw我的意思是,而不是hex2bin,不用於加密o.O – Manhim

0

mcrypt_encrypt已經以字符串的形式返回加密數據 - 爲什麼要經過進一步的轉換?如果你擔心傳輸(例如電子郵件),那麼你可以在加密之後使用base64 encode/decode,如果你擔心數據庫的存儲,只要確保你轉義了SQL中的字符串(或使用數據庫參數)即可。

此外,「最好不要使用ASCII字符串鍵」。嘗試改爲:

$key=hash("SHA256", "TestingKey", true); 
0

你可以用兩個簡單的功能:

define('SALT', 'your secret salt'); 

function encrypt($text) 
{ 
    return trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, SALT, $text, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND)))); 
} 

function decrypt($text) 
{ 
    return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, SALT, base64_decode($text), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND))); 
} 
+1

你不需要對同一個加密字符串使用相同的IV嗎?或者我只是在加密失敗? – Manhim

3

更改您的hex2bin()功能以下內容,你的腳本的其餘部分將工作得很好。

function hex2bin($text) 
{ 
    return pack('H*', $text); 
} 

對於它的價值,「丟失」的hex2bin()功能是recently added到PHP源代碼,很可能會用PHP 5.4.0發佈。

2

爲什麼你使用hexbin?只需使用PHP的mcrypt_decrypt()和mycrypt_encrypt()函數即可完成。它們基本上採用相同的參數,唯一的區別是您傳遞給它的數據字符串的狀態。

PHP.net說:

mcrypt_encrypt(字符串$密碼,字符串$鍵,字符串$數據,串$模式[,字符串$ IV]) mcrypt_decrypt(字符串$密碼,字符串$鍵,字符串$數據,串$模式[,串$ IV])

因此,這裏是一些示例代碼我鞭打在一起你...

<?php 
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB); 
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND); 

$key = "This is a very secret key"; 
$text = "Meet me at 11 o'clock behind the monument."; 

//Lets encrypt it 
$encrypted_text = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB, $iv); 
echo "Here is the encrypted text: $encrypted_text\n<br>\n"; 

//Do whatever with it. Store it, transmit it, whatever... 

//Ok, I want it back. Lets decrypt it. 
$decrypted_text = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $encrypted_text, MCRYPT_MODE_ECB, $iv); 

//Hooray, the data is back! 
?>