2015-09-15 44 views
4

C#代碼看起來像這樣(無法將其更改爲客戶端系統中的代碼)。在C#中使用TripleDES加密的字符串需要使用PHP解密

namespace Common { 
public static class EncryptionHelper 
{ 

    private const string cryptoKey = "password"; 

// The Initialization Vector for the DES encryption routine 
    private static readonly byte[] IV = new byte[8] { 240, 3, 45, 29, 0, 76, 173, 59 }; 

/// <summary> 
/// Encrypts provided string parameter 
/// </summary> 
public static string Encrypt(string s) 
{ 

    string result = string.Empty; 

    byte[] buffer = Encoding.ASCII.GetBytes(s); 

    byte[] k = Encoding.ASCII.GetBytes(cryptoKey); 

    TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider(); 
    MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider(); 


    des.Key = MD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(cryptoKey)); 

    des.IV = IV; 

    result = Convert.ToBase64String(des.CreateEncryptor().TransformFinalBlock(buffer, 0, buffer.Length)); 

    return result; 
    } 
} 
} 

我發現客戶端把這個班從這裏:http://johnnycoder.com/blog/2008/07/03/c-encryption-decryption-helper-class/

我不是很熟悉C#,我需要在PHP解密字符串 此代碼加密。

當我做「md5($ key,true)」我得不到與「MD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(cryptoKey));」相同的結果,不知道爲什麼。

如何將「byte [] IV」轉換爲PHP字符串?

任何幫助,將不勝感激。 謝謝。

+0

你肯定'MD5.ComputeHash()',甚至是你的C#類,返回原始二進制散列? 'md5($ key,true)'_will_輸出原始二進制散列,所以這可能是你的不一致的根源。 – Fuselight

+0

我已經設法得到相同的MD5字符串,但仍然無法解密它。 – staskus

回答

2

設法得到它的工作:

class Crypter 
{ 

/** 
* 
* Encryption key 
* 
* @var 
*/ 
protected $key; 

/** 
* 
* Encryption vector 
* 
* @var 
*/ 
protected $iv; 

public function __construct() 
{ 

    $this->key = config('auth.triple_des_key'); 
    $this->iv = implode(array_map("chr", config('auth.triple_des_iv'))); 
} 


/** 
* 
* Decrypts string using tripleDES method. 
* 
* @param $input String 
* @return String 
*/ 
public function decryptTripleDES($input) 
{ 

    $td = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_CBC, ''); 

    $encryptedData = base64_decode($input); 

    $key = iconv('utf-8', 'us-ascii//TRANSLIT', $this->key); 

    $key = md5($key, true); 
    $key .= substr($key, 0, 8); 

    mcrypt_generic_init($td, $key, $this->iv); 

    $decryptedData = mdecrypt_generic($td, $encryptedData); 
    mcrypt_generic_deinit($td); 

    //remove the padding text 
    $block = mcrypt_get_block_size("tripledes", "cbc"); 

    $packing = ord($decryptedData{strlen($decryptedData) - 1}); 

    if ($packing and ($packing < $block)) { 
     for ($P = strlen($decryptedData) - 1; $P >= strlen($decryptedData) - $packing; $P--) { 
      if (ord($decryptedData[$P]) != $packing) { 
       $packing = 0; 
      } 
     } 
    } 

    $decryptedData = substr($decryptedData, 0, strlen($decryptedData) - $packing); 

    return $decryptedData; 
} 
} 
相關問題