2013-09-23 94 views
0

我有一個系統由兩部分組成--C++和c#應用程序。這部分有一個共享的文件,可以讀取和寫入。爲了防止來自普通用戶的文件,我使用AES加密。 C++應用程序使用openSSL ctypto庫AES實現和C#應用程序使用.NET Framework System.Security.Cryptography。爲了加密,我使用CBC模式。某些應用程序中的加密/解密工作良好,但是當我嘗試在一個應用程序(C++)來加密,而在另一個(C#)解密我面對異常:在C++(OpenSSL)中加密AES,在C#中解密

填充無效,不能刪除

我的測試是通過在C++應用程序中加密32字節的明文數據,然後將其寫入文件,然後在C#應用程序中讀取和解密嘗試。 我做解密的方式如下:

using (AesCryptoServiceProvider aesEncryptor = new AesCryptoServiceProvider()) 
{ 
    aesEncryptor.Mode = CipherMode.CBC; 
    aesEncryptor.Key = entropy; 

    // it's the same in C++ application too 
    byte[] iv = { 0x46, 0xb6, 0x02, 0x6a, 
        0x99, 0x21, 0x90, 0xde, 
        0xfd, 0xf4, 0x5b, 0x42, 
        0x94, 0xde, 0xa6, 0x23 }; 
    aesEncryptor.IV = iv; 

    using (ICryptoTransform decryptor = aesEncryptor.CreateDecryptor(aesEncryptor.Key, 
                    aesEncryptor.IV)) 
    { 
     byte[] decrypted; 
     // Create the streams used for decryption. 
     using (MemoryStream msDecrypt = new MemoryStream(encryptedData)) 
     { 
      using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, 
                  decryptor, 
                  CryptoStreamMode.Read)) 
      { 
       decrypted = new byte[encryptedData.Length]; 
       var byteCount = csDecrypt.Read(decrypted, 0, encryptedData.Length); 
       return decrypted; 

      } 
     } 
    } 
} 

我公司還提供完整的例外應將描述:

$異常{System.Security.Cryptography.CryptographicException: 填充是無效的,不能刪除。在 System.Security.Cryptography.CapiSymmetricAlgorithm.DepadBlock(字節[] 塊,的Int32偏移的Int32計數)在 System.Security.Cryptography.CapiSymmetricAlgorithm.TransformFinalBlock(字節[] INPUTBUFFER,的Int32 inputOffset,的Int32 inputCount)在 System.Security.Cryptography.CryptoStream.FlushFinalBlock()在 System.Security.Cryptography.CryptoStream.Dispose(布爾處置)
вSystem.IO.Stream.Close()在System.IO.Stream.Dispose()

+0

沒有C++代碼很難說出什麼問題。 – zindorsky

回答

1

你不給你的加密代碼,但是例外情況表明用於加密的填充模式不同於填充在C#中解密時使用的模式(這將是默認的填充模式:PaddingMode.PKCS7)。

檢查加密時使用的填充模式,並確保使用相同的模式進行解密。 .NET中可用模式的列表可用here

+0

將PaddingMode設置爲None解決了此問題。現在可以用兩種方式加密/解密。 – vard