2009-06-24 60 views
2

我在一端有一個PHP解密算法,另一端有一個.Net加密算法。我在PHP代碼中使用mcrypt_decrypt進行解密,並在.Net中查找等效的mcrypt_encrypt。更具體地講,我要轉換爲.NET中的PHP代碼如下:MCRYPT in .Net

$cipher_alg = MCRYPT_RIJNDAEL_128; 
$iv = mcrypt_create_iv (mcrypt_get_iv_size ($cipher_alg, MCRYPT_MODE_ECB), MCRYPT_RAND); 

$encrypted_string = mcrypt_encrypt ($cipher_alg, $sessionkey, $string, MCRYPT_MODE_CBC, $iv); 
$hex_encrypted_string = bin2hex ($encrypted_string); 

是否存在的mcrypt_encrypt在.net中的相同呢?

+0

`mcrypt_create_iv()'+'MCRYPT_MODE_ECB`是一個昂貴的`NOP`。 – 2016-02-24 21:04:32

回答

3

我跟a solution in my blog出來了。

下面是摘錄:

private static string CreateEncryptedString(string myString, string hexiv, string key) 
    { 
     RijndaelManaged alg = new RijndaelManaged(); 
     alg.Padding = PaddingMode.Zeros; 
     alg.Mode = CipherMode.CBC; 
     alg.BlockSize = 16 * 8; 
     alg.Key = ASCIIEncoding.UTF8.GetBytes(key); 
     alg.IV = StringToByteArray(hexiv); 
     ICryptoTransform encryptor = alg.CreateEncryptor(alg.Key, alg.IV); 

     MemoryStream msStream = new MemoryStream(); 
     CryptoStream mCSWriter = new CryptoStream(msStream, encryptor, CryptoStreamMode.Write); 
     StreamWriter mSWriter = new StreamWriter(mCSWriter); 
     mSWriter.Write(myString); 
     mSWriter.Flush(); 
     mCSWriter.FlushFinalBlock(); 

     var EncryptedByte = new byte[msStream.Length]; 
     msStream.Position = 0; 
     msStream.Read(EncryptedByte, 0, (int)msStream.Length); 

     return ByteArrayToHexString(EncryptedByte); 

    } 

    public static byte[] StringToByteArray(String hex) 
    { 
     int NumberChars = hex.Length; 
     byte[] bytes = new byte[NumberChars/2]; 
     for (int i = 0; i < NumberChars; i += 2) 
      bytes[i/2] = Convert.ToByte(hex.Substring(i, 2), 16); 
     return bytes; 
    } 

    public static string ByteArrayToHexString(byte[] ba) 
    { 
     StringBuilder hex = new StringBuilder(ba.Length * 2); 
     foreach (byte b in ba) 
      hex.AppendFormat("{0:x2}", b); 
     return hex.ToString(); 
    } 

有一兩件事要注意。密鑰大小必須爲16.這意味着密鑰參數必須是包含16個字符的字符串。否則加密將不起作用,並會拋出CryptographicException。

在PHP結束,這裏是你如何做到解碼:

$cipher_alg = MCRYPT_RIJNDAEL_128; 
$decrypted_string = mcrypt_decrypt($cipher_alg, $key, 
$encrypted_string , MCRYPT_MODE_CBC, trim(hex2bin(trim($hexiv)))); 
1

沒有直接的等價物,但支持128位Rijndael(也可能是大多數其他的密碼)。有關詳細信息和示例,請參閱Rijndael課程。

基本上,框架的加密部分基於您指定基類的適當實例(CryptoStreamSymmetricAlgorithm等),而不是按名稱指定密碼 - 但您應該能夠執行所需的操作。