I have a system consists of two parts - c++ and c# application. This parts have a shared file which both could read and write. To defend my file from regular user I use AES encryption. C++ application use openSSL ctypto library AES implementation and C# application uses .NET Framework System.Security.Cryptography. For encryption I use CBC mode. Encryption/Decryption within certain application works good, but when I try to encrypt in one application(C++) and decrypt in another(C#) I face exception:
padding is invalid and cannot be removed
My test is performed by encryption 32 bytes of plain data in C++ application, then writing it in file then reading and decryption attempt in C# application.
I make decryption in following manner:
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;
}
}
}
}
I also provide full exception desciption:
$exception {System.Security.Cryptography.CryptographicException:
padding is invalid and cannot be removed. in
System.Security.Cryptography.CapiSymmetricAlgorithm.DepadBlock(Byte[]
block, Int32 offset, Int32 count) in
System.Security.Cryptography.CapiSymmetricAlgorithm.TransformFinalBlock(Byte[]
inputBuffer, Int32 inputOffset, Int32 inputCount) in
System.Security.Cryptography.CryptoStream.FlushFinalBlock() in
System.Security.Cryptography.CryptoStream.Dispose(Boolean disposing)
в System.IO.Stream.Close() in System.IO.Stream.Dispose()