2015-02-23 30 views
0

嗨,大家好,我已經使用AesCbc方法在PHP中以字符串的形式對單詞hello進行了加密。這是我的代碼。如何在php5中加密和解密在windows store 8.1和c#中使用aescbc

base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128,'123456789',pkcs7_pad('hello', 16),MCRYPT_MODE_CBC)) 

結果是

67fHA+Z12z2jlwOLTBeCPA== 

我那麼這個結果發送到我的Windows Store應用程序,這是我使用的解密功能。

 public string AES_Decrypt(string input, string pass) 
    { 
     SymmetricKeyAlgorithmProvider SAP = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbc); 
     CryptographicKey AES; 
     HashAlgorithmProvider HAP = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5); 
     CryptographicHash Hash_AES = HAP.CreateHash(); 

     string decrypted = ""; 
     try 
     { 
      byte[] hash = new byte[32]; 
      Hash_AES.Append(CryptographicBuffer.CreateFromByteArray(System.Text.Encoding.UTF8.GetBytes(pass))); 
      byte[] temp; 
      CryptographicBuffer.CopyToByteArray(Hash_AES.GetValueAndReset(), out temp); 

      Array.Copy(temp, 0, hash, 0, 16); 
      Array.Copy(temp, 0, hash, 15, 16); 

      AES = SAP.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(hash)); 

      IBuffer Buffer = CryptographicBuffer.DecodeFromBase64String(input); 
      byte[] Decrypted; 
      CryptographicBuffer.CopyToByteArray(CryptographicEngine.Decrypt(AES,Buffer,null), out Decrypted); 
      decrypted = System.Text.Encoding.UTF8.GetString(Decrypted, 0, Decrypted.Length); 

      return decrypted; 
     } 
     catch (Exception ex) 
     { 
      return null; 
     } 
    } 

結果是這樣的

7��t�\a2H\0��g 

當它應該是 「你好」。 那麼我的代碼在哪裏出錯?

回答

0

密鑰不在您的PHP代碼中散列。所以,不要在C#中做:

AES = SAP.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(
    System.Text.Encoding.UTF8.GetBytes(pass) 
));