Question:
I am trying to encrypt a file using AES in a C# program and decrypt it in a C++ (non-managed code) program using the Chilkat components. Everything compiles, runs, etc and a file is output from the decryption method, it is just not decrypted correctly and is unreadable.
Any idea what I am missing? I assume it is a setting of some sort…
Here are the methods:
C#
private void EncryptFileAES()
{
Chilkat.Crypt2 cryptComponent = new Chilkat.Crypt2();
bool bSuccess = cryptComponent.UnlockComponent("****");
// Set the encryption parameters.
cryptComponent.CryptAlgorithm = "rijndael"; //AES Encryption
cryptComponent.SecretKey = cryptComponent.GenerateSecretKey("abc");
cryptComponent.KeyLength = 256;
//Encrypt the file
cryptComponent.CkEncryptFile(srcFile, targetFile);
}
C++
DecryptFileAES()
{
CkCrypt2 crypt;
bool bret = crypt.UnlockComponent("***");
crypt.put_CryptAlgorithm("aes");
crypt.put_KeyLength(256);
CkByteData secretKey;
crypt.GenerateSecretKey("abc", secretKey);
crypt.put_SecretKey(secretKey);
//Decrypt the file
bool bret = crypt.CkDecryptFile(srcFile, destFile);
}
Answer:
The GenerateSecretKey method returns a byte array equal in length to the number of bits in
the KeyLength property. Therefore, it must be called *after* the KeyLength is set:
cryptComponent.KeyLength = 256;
cryptComponent.SecretKey = cryptComponent.GenerateSecretKey("abc");
(The default KeyLength is 128-bits, so the SecretKey will be 16 bytes if you call GenerateSecretKey prior to setting the KeyLength equal to 256.)
If you make this change in the C# code above, everything should work.