C#에서 RijndaelManaged를 사용하여 데이터를 암호화하고 C++ 코드에서 해독해야합니다.Windows AES 암호화 공급자를 사용하여 C++에서 C# 암호화 된 데이터를 암호 해독
C# 암호화 코드 :
static string Encrypt(string plainText)
{
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
var keyBytes = new byte[] { /* ... 32 bytes of a key */};
byte[] iv = new byte[] { /* ... 16 bytes of IV */ };
var symmetricKey = new RijndaelManaged()
{
Mode = CipherMode.CBC,
Padding = PaddingMode.Zeros,
BlockSize = 128, // Must be 128 to be compatible with AES
KeySize = 256
};
var encryptor = symmetricKey.CreateEncryptor(keyBytes, iv);
byte[] cipherTextBytes;
using(var memoryStream = new MemoryStream())
{
using(var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
cipherTextBytes = memoryStream.ToArray();
cryptoStream.Close();
}
memoryStream.Close();
}
return Convert.ToBase64String(cipherTextBytes);
}
그러나 C++ 코드를 암호 해독 할 때 나는 항상를 CryptDecrypt에서 응답 NTE_BAD_DATA 얻을.
__declspec(dllexport) DWORD Decrypt(char* stringBuffer)
{
string encryptedString(stringBuffer);
// Decode base64 string to byte array. Works ok, the binary array is the same as the one in C# code.
vector<BYTE> encryptionBuffer = Base64::decode(encryptedString);
DWORD bufferSize = encryptionBuffer.size();
struct CryptoBlob {
BLOBHEADER header;
DWORD cbKeySize;
BYTE rgbKeyData[32];
} keyBlob;
keyBlob.header.bType = PLAINTEXTKEYBLOB;
keyBlob.header.bVersion = CUR_BLOB_VERSION;
keyBlob.header.reserved = 0;
keyBlob.header.aiKeyAlg = CALG_AES_256;
keyBlob.cbKeySize = 32;
BYTE keyData[32] = { /* 32 bytes of a key the same as in C# code */ };
BYTE ivData[16] = { /* 16 bytes of IV the same as in C# code */ };
memcpy(keyBlob.rgbKeyData, keyData, 32);
HCRYPTKEY hPubKey;
HCRYPTPROV hProv;
CryptAcquireContext(
&hProv,
NULL,
NULL,
PROV_RSA_AES,
CRYPT_VERIFYCONTEXT);
CryptImportKey(hProv, (const LPBYTE)&keyBlob, sizeof(keyBlob), 0, 0, &hPubKey);
CryptSetKeyParam(hPubKey, KP_IV, ivData, 0);
// Here the error happens, the value returned is 0x80090005 (NTE_BAD_DATA)
DWORD err = CryptDecrypt(hPubKey, 0, TRUE, 0, encryptionBuffer.data(), &bufferSize);
// overwrite the input buffer with decrypted data
memset(stringBuffer, 0, encryptedString.length());
memcpy(stringBuffer, encryptionBuffer.data(), bufferSize);
return 0;
}
어떤 생각이 잘못 될 수 있는지 : 여기에 (모든 검사가 명확성을 위해 제거) C++ 코드는? 감사합니다.
필자는 * 패딩 *과 관련된 동일한 문제에 대한 여러 참조를 조사한 바 있습니다. 여기를 확인하십시오 : [CryptoAPI CryptDecrypt 함수 NT_BAD_DATA 오류] (https://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/e2735c15-afe8-4f86-abb8-14e987fb0ccd/cryptoapi-cryptdecrypt-function-ntbaddata-error ? forum = vcgeneral) 여기에 : [CryptDecrypt function] (https://msdn.microsoft.com/ko-kr/library/windows/desktop/aa379913(v=vs.85)asp) (NTE_BAD_DATA 오류 코드). –