我已经对此进行了更新,以更全面地描述正在发生的事情。希望我没有违反任何规则。
第二次更新:在应用程序端更改了解密(在“以下内容改编自...之后”)。
我有一个文本文件,我在源计算机上对其进行了加密。需要将生成的文件分发到许多目标计算机,并在运行中对其进行解密以进行呈现。传输安全性不是问题;我们主要关注的是出于报告目的的数据完整性;最终用户应该不能编辑自由文本文件,因此不能进行加密。在源计算机上,我的加密和解密工作正常。这是源加密:
HCRYPTPROV m_hCryptProv;
HCRYPTKEY m_hSigKey;
HCRYPTKEY m_hExchKey;
HCRYPTHASH m_hHash;
CMemFile m_file;
CString m_strPassword;
CString m_strData;
CByteArray arData;
CFile file;
DWORD dwBlobLen = 0;
BYTE* pbKeyBlob;
CryptAcquireContext(&m_hCryptProv, NULL, NULL, PROV_RSA_FULL, 0);
CryptCreateHash(m_hCryptProv, CALG_MD5, 0, 0, &m_hHash);
CryptHashData(m_hHash, (const BYTE*)strPassword.GetString(), strPassword.GetLength() * sizeof(TCHAR), 0);
CryptDeriveKey(m_hCryptProv, CALG_RC2, m_hHash, CRYPT_EXPORTABLE, &m_hSigKey);
// m_strData is input to be encrypted
m_crypto.Encrypt(m_strData, arData);
file.Write(arData.GetData(), static_cast<UINT>(arData.GetCount()));
file.Flush();
file.Close();
// encrypted file "file" copied to target machine as "GlobalOperator.dat".
// Generate exchange key and write to file.
CryptGetUserKey(m_hCryptProv, AT_KEYEXCHANGE, &m_hExchKey);
CryptExportKey(m_hExchKey, 0, PUBLICKEYBLOB, 0, NULL, &dwBlobLen);
pbKeyBlob = (BYTE*)malloc(dwBlobLen);
//CryptExportKey(m_hExchKey, 0, PUBLICKEYBLOB, 0, NULL, &dwBlobLen);
CryptExportKey(m_hExchKey, 0, PUBLICKEYBLOB, 0, pbKeyBlob, &dwBlobLen);
file.Write(pbKeyBlob, dwBlobLen);
file.Flush();
file.Close();
// key file "file" copied to target machine as "key.dat".
目标计算机运行应用程序,尝试读取加密的文件:
CString m_strData;
CByteArray arData;
CFile GlobalOperatorFile;
GlobalOperatorFile.Open("GlobalOperator.dat")
arData.SetSize(static_cast<INT_PTR>(GlobalOperatorFile.GetLength()));
GlobalOperatorFile.Read(arData.GetData(), static_cast<UINT>(GlobalOperatorFile.GetLength()));
GlobalOperatorFile.Close();
// Try to deserialize the data.
DWORD dwBlobLen = 0;
CMemFile m_file;
m_file.SetLength(0);
// Write the contents of the byte array to the memory file.
m_file.Write(arData.GetData(), static_cast<UINT>(arData.GetCount()));
m_file.Flush();
// Acquire direct access to the memory file buffer.
BYTE* pData = m_file.Detach();
DWORD dwDataLength = static_cast<DWORD>(arData.GetCount());
// The following adapted from https://docs.microsoft.com/en-us/windows/win32/seccrypto/example-c-program-decrypting-a-file
CryptCreateHash(m_hCryptProv, CALG_MD5, 0, 0, &m_hHash);
CString pwd = "EncryptionKey";
CryptHashData(m_hHash, (const BYTE*)pwd.GetString(), pwd.GetLength() * sizeof(TCHAR), 0);
CryptDeriveKey(m_hCryptProv, CALG_RC2, m_hHash, CRYPT_EXPORTABLE, &m_hKey);
CryptDecrypt(m_hKey, NULL, TRUE, 0, pData, &dwDataLength);
// The above call to CryptDecrypt fails with error code 0x80090005: NTE_BAD_DATA
因此,我显然不知道我正在使用加密/解密做什么。
有人可以帮忙吗?