我想用wincrypt解密一個文件,我似乎無法正確解密這個函數。這些字節是用C#中的RC2實現加密的,我爲加密和解密過程(在C#中加密,在C++中解密)提供了相同的密碼和IV。Wincrypt:無法解密在C#中加密的文件。 NTE_BAD_DATA CryptDecrypt
沿途的所有函數都返回true,直到最終的「CryptDecrypt」函數。而不是我打字出來,這裏是功能:
static char* DecryptMyFile(char *input, char *password, int size)
{
HCRYPTPROV provider = NULL;
if(CryptAcquireContext(&provider, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, 0))
{printf("Context acquired.");}
else
{
if (GetLastError() == NTE_BAD_KEYSET)
{
if(CryptAcquireContext(&provider, 0, NULL, PROV_RSA_FULL, CRYPT_NEWKEYSET))
{printf("new key made.");}
else
{
printf("Could not acquire context.");
}
}
else
{printf("Could not acquire context.");}
}
HCRYPTKEY key = NULL;
HCRYPTHASH hash = NULL;
if(CryptCreateHash(provider, CALG_MD5, 0, 0, &hash))
{printf("empty hash created.");}
else
{printf("could not create hash.");}
if(CryptHashData(hash, (BYTE *)password, strlen(password), 0))
{printf("data buffer is added to hash.");}
else
{printf("error. could not add data buffer to hash.");}
if(CryptDeriveKey(provider, CALG_RC2, hash, 0, &key))
{printf("key derived.");}
else
{printf("Could not derive key.");}
DWORD dwKeyLength = 128;
if(CryptSetKeyParam(key, KP_EFFECTIVE_KEYLEN, reinterpret_cast<BYTE*>(&dwKeyLength), 0))
{printf("success");}
else
{printf("failed.");}
BYTE IV[8] = {0,0,0,0,0,0,0,0};
if(CryptSetKeyParam(key, KP_IV, IV, 0))
{printf("worked");}
else
{printf("faileD");}
DWORD dwCount = size;
BYTE *decrypted = new BYTE[dwCount + 1];
memcpy(decrypted, input, dwCount);
decrypted[dwCount] = 0;
if(CryptDecrypt(key,0, true, 0, decrypted, &dwCount))
{printf("succeeded");}
else
{printf("failed");}
return (char *)decrypted;
}
輸入是傳遞給函數,加密的數據。密碼與用於加密C#中的數據的密碼相同。大小是加密時數據的大小。
所有上述函數返回true直到CryptDecrypt,我似乎無法弄清楚爲什麼。同時,我不確定CryptDecrypt函數如何編輯我的「解密」變量,因爲我沒有傳遞它的參考。
任何幫助或建議,爲什麼這是行不通的將不勝感激。這是我第一次使用Wincrypt和第一次使用C++的努力。
如果它是任何更多的幫助,還有,這是我的加密(在C#):
public static byte[] EncryptString(byte[] input, string password)
{
PasswordDeriveBytes pderiver = new PasswordDeriveBytes(password, null);
byte[] ivZeros = new byte[8];
byte[] pbeKey = pderiver.CryptDeriveKey("RC2", "MD5", 128, ivZeros);
RC2CryptoServiceProvider RC2 = new RC2CryptoServiceProvider();
//using an empty initialization vector for convenience.
byte[] IV = new byte[8];
ICryptoTransform encryptor = RC2.CreateEncryptor(pbeKey, IV);
MemoryStream msEncrypt = new MemoryStream();
CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
csEncrypt.Write(input, 0, input.Length);
csEncrypt.FlushFinalBlock();
return msEncrypt.ToArray();
}
我已經證實,在C++中我的哈希值是相同的我在C#中的關鍵,通過創建PasswordDeriveBytes.CryptDeriveKey
你應該調用GetLastError()來獲取錯誤代碼(NTE_BAD_DATA,NTE_BAD_KEY,NTE_BAD_LEN等) – 2009-10-09 23:10:01
正確。我做了並得到了壞數據。 – Chris 2009-10-09 23:14:07