2011-08-09 37 views
0

我試圖在PHP中使用此函數加密數據,並使用C#中的其他函數對其進行解密。但我沒有得到相同的字符串。在PHP中加密AES,在C#中解密

//php function 
    public function onCrypt($text) 
    { 
    $key=md5('DFDFDFDFDFDFDFDFDFDFDFDF',true); 

    $crypttext = urldecode(trim(mcrypt_encrypt(MCRYPT_RIJNDAEL_128,$key, $text, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB), MCRYPT_RAND)))); 

    $text_crp =base64_encode($crypttext); 


    return $text_crp; 
      } 

// C#功能

//公共靜態無效DecryptFile 參數: strKey:在解密選用的關鍵。 PathPlainTextFile:加密文件的路徑 PathPlainTextFile:解密原始文件。

public static void DecryptFile(string strKey, string pathPlainTextFile, string pathCypheredTextFile)  
    { 

//crypt key with md5 function   
System.Security.Cryptography.MD5 alg = System.Security.Cryptography.MD5.Create(); 
System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding(); 
byte[] md5val = alg.ComputeHash(enc.GetBytes(strKey)); 


StreamReader fsPlainTextFile = File.OpenText(pathPlainTextFile);  
FileInfo t = new FileInfo(pathCypheredTextFile); 
StreamWriter Tex =t.CreateText(); 
string input = null; 
while ((input = fsPlainTextFile.ReadLine()) != null) 
{ 


     byte[] cipheredData = Convert.FromBase64String(input); 

      RijndaelManaged rijndaeld = new RijndaelManaged(); 

      // define the used mode 
      rijndaeld.Mode = CipherMode.ECB; 

      // create the cipher AES - Rijndael 
      ICryptoTransform decryptor = rijndaeld.CreateDecryptor(md5val,null); 

      // Write the ciphered data in MemoryStream 
      MemoryStream ms= new MemoryStream(cipheredData); 
      CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read); 

       // Insert the ciphered data in a byte array 
       byte[] plainTextData = new byte[cipheredData.Length]; 

      int decryptedByteCount = cs.Read(plainTextData, 0, plainTextData.Length); 

      ms.Close(); 
      cs.Close(); 


    // Insert the ciphered data in string encoded on Base64   
Tex.WriteLine (Encoding.UTF8.GetString(plainTextData, 0, decryptedByteCount)); 





} 

Tex.Close();  


    } 

回答

0

快速瀏覽,你不提供一個四到C#解密:

ICryptoTransform decryptor = rijndaeld.CreateDecryptor(md5val, null); 

我不熟悉PHP,但它看起來像你創建了一個IV當你加密內容。你需要有相同的IV才能在C#代碼中解密它(即使你通過php進行解密,你也需要相同的IV來解密它)。

+0

rijndaeld.Padding = Padding.zero; –

+0

我嘗試我的解決方案,但我認爲它的答案相同 –

+0

ECB模式不使用任何IV。 –

1

ECB模式不安全。您應該使用CTR模式或CBC模式。最好還是明確指定要在兩端使用的填充。

+0

但我不想將矢量IV保存在數據庫中 –

+0

CTR模式不需要IV,只是一個隨機數,它可以更小。 – rossum