I have two programs that need to work together encrypting and decrypting text. One, which is in C# and runs in .NET, has a simple encryption and decryption scheme. The other, which cannot run in .NET, runs in Win32 and is written in C/C++. The Win32 piece needs to encrypt data so that the .NET piece can decrypt it. I have implemented the both the .NET code and the Win32 piece using the sample code provided by Microsoft, and they work fine encrypting and decrypting data by themselves. However, whenever I try to encrypt data from Win32, the .NET is unable to decrypt it, throwing an exception as "Bad data." I have written the .NET piece using the TripleDESCryptoServiceProvider class, and the Win32 using the CryptoAPI. I am not certain just what I need to do to get equivalent results. The .NET encryption code is simple and straightforward, but I am not certain just what the "magic" is underneath:
TripleDESCryptoServiceProvider _desProvider = new TripleDESCryptoServiceProvider();
byte[] keyBytes;
byte[] vectorBytes;
FileStream fStream = File.Open(locationOfFile, FileMode.Create, FileAccess.Write);
CryptoStream cStream = new CryptoStream(fStream,
_desProvider.CreateEncryptor(keyBytes, vectorBytes),
CryptoStreamMode.Write);
BinaryWriter bWriter = new BinaryWriter(cStream);
byte[] rawData;
bWriter.Write(rawData);
What would be the equivalent code using the Crypto API? Do I need to call CryptDeriveKey(), create a hash code with the key bytes, put something into the name of the provider, import a key, etc.?
I've tried something like:
byte[] keyBytes;
byte[] vectorBytes;
if(CryptAcquireContext(&hProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
{
HCRYPTKEY hKey = NULL;
{
if(CryptSetKeyParam(hKey, KP_IV, vectorbytes, 0))
{
BYTE filebytes[2048];
DWORD cbEncrypted, dwSize;
if (CryptEncrypt(hKey, NULL, TRUE, 0, filebytes, &cbEncrypted, dwSize))
{
}
}
CryptDestroyKey(hKey);
hKey = NULL;
}
}
I've looked at a couple of Microsoft sites for sample code (
http://msdn.microsoft.com/en-us/library and
http://msdn.microsoft.com/en-us/library/aa382358(VS.85).aspx[
^]), but I haven't been able to get it to work with the .NET decryption. What am I doing wrong?