2013-09-23 35 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