2012-12-28 38 views
0

我需要在PHP中的3DES字符串解碼和我在至今decripting沒有經驗......3DES在PHP - 不能得到良好的鍵/串

第一步是:拿到鑰匙和一套要解碼的字符串 - 我已經有了。

我對algorythm信息:

類型: - (IV)CBC, 填充PKCS5, 初始化向量 - 的八個零

陣列我試着這樣說:

// very simple ASCII key and IV 
$key = "[email protected]"; 
$iv = "password"; 
//$iv = array('0','0','0','0','0','0','0','0'); 
//$iv = "00000000"; 

$cipher = mcrypt_module_open(MCRYPT_3DES, '', 'cbc', ''); 

//$iv = mcrypt_enc_get_iv_size($cipher); 


// DECRYPTING 
echo "<b>String to decrypt:</b><br />51196a80db5c51b8523220383de600fd116a947e00500d6b9101ed820d29f198c705000791c07ecc1e090213c688a4c7a421eae9c534b5eff91794ee079b15ecb862a22581c246e15333179302a7664d4be2e2384dc49dace30eba36546793be<br /><br />"; 

echo "<b>Decrypted 3des string:</b><br /> ".SimpleTripleDesDecrypt('51196a80db5c51b8523220383de600fd116a947e00500d6b9101ed820d29f198c705000791c07ecc1e090213c688a4c7a421eae9c534b5eff91794ee079b15ecb862a22581c246e15333179302a7664d4be2e2384dc49dace30eba36546793be')."<br />"; 

function SimpleTripleDesDecrypt($buffer) { 
    global $key, $iv, $cipher; 

    mcrypt_generic_init($cipher, $key, $iv); 
    $result = rtrim(mdecrypt_generic($cipher, hex2bin($buffer)), "\0"); 
    mcrypt_generic_deinit($cipher); 
    return $result; 
} 

function hex2bin($data) 
{ 
    $len = strlen($data); 
    return pack("H" . $len, $data); 
} 

在beginnig中,您會看到示例數據,並且此數據代碼正常工作。當我嘗試使用通過SOAP webservice從數據庫獲得的自己的數據時,問題就開始了。我看到這個錯誤:

警告:包()[function.pack]:H型:非法十六進制數字的....

enter image description here

我得到這個,儘管有不同類型的製作嘗試在腳本中編碼。腳本文件本身在ANCI中。

另外:正如你在評論中看到的,我也用IV做了一些實驗,但沒有處理第一個問題就沒有意義了。

另一件事是填充== PKCS5。我需要使用它嗎?在我的情況下,我該怎麼做?

我真的很感謝這方面的幫助。

+0

可能重複http://stackoverflow.com/questions/8530312/php-equivalent-for-java-triple- des-encryption-decryption) –

回答

0

好吧,我發現一個解決方案主要基於這個職位:PHP Equivalent for Java Triple DES encryption/decryption - thanx傢伙和+1。

$iv = array('0','0','0','0','0','0','0','0'); 
echo @decryptText($temp->patient->firstName, $deszyfrator->return->rawDESKey, $iv); 
echo @decryptText($temp->patient->surname, $deszyfrator->return->rawDESKey, $iv); 

function decryptText($encryptText, $key, $iv) { 

    $cipherText = base64_decode($encryptText); 
    $res = mcrypt_decrypt("tripledes", $key, $cipherText, "cbc", $iv); 

    $resUnpadded = pkcs5_unpad($res);  
    return $resUnpadded; 
} 

function pkcs5_unpad($text) 
{ 
    $pad = ord($text{strlen($text)-1}); 
    if ($pad > strlen($text)) return false; 
    if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) return false; 
    return substr($text, 0, -1 * $pad); 
} 

但是我得到一個警告(隱藏在@現在)。 「Iv應該和塊大小一樣長 - 」我嘗試了所有我能弄清楚的組合,我無法擺脫它。任何想法的人?

編輯:二級問題修復。此KODE將解決IV:

$iv_size=mcrypt_get_iv_size("tripledes","cbc"); 
$iv = str_repeat("\0", $iv_size); //iv size for 3des is 8 
[對Java三重DES加密/解密PHP等效](的
+0

請不要在答案中提出額外的問題,反而會產生新的問題(當然在調試之後)。 –

+0

Thx爲輸入貓頭鷹。我問了第二個問題,以便爲最初的問題提供最好的解決方案。現在所有的作品都很好。 –

+0

很高興聽到那個男爵... –