bool CCrypto::Decrypt(const CByteArray& arData, CObject& serializable)
{
// Return failure if we don't have a context or key.
if(m_hCryptProv == NULL || m_hKey == NULL)
return false;
// Return failure if the object is not serializable.
if(serializable.IsSerializable() == FALSE)
return false;
// Decrypt the contents of the array to the memory file.
if(InternalDecrypt(arData) == false)
return false;
// Create a reading archive from the memory file.
CArchive ar(&m_file, CArchive::load);
// Read the data from the memory file.
serializable.Serialize(ar);
// Close the archive.
ar.Close();
// And we're done.
return true;
}
// =============================================================================
bool CCrypto::InternalDecrypt(const CByteArray& arSource)
{
// Trash the file.
m_file.SetLength(0);
// Write the contents of the byte array to the memory file.
m_file.Write(arSource.GetData(), static_cast<UINT>(arSource.GetSize())); //.GetCount()));
m_file.Flush();
// Acquire direct access to the memory file buffer.
BYTE* pData = m_file.Detach();
// We need a DWORD to tell decrpyt how much data we're encrypting.
DWORD dwDataLength = static_cast<DWORD>(arSource.GetSize()); //.GetCount());
// DWORD dwOldDataLength = dwDataLength;
// Now decrypt the data.
if(!::CryptDecrypt(m_hKey, NULL, TRUE, 0, pData, &dwDataLength))
{
// Free the memory we release from the memory file.
delete [] pData;
return false;
}
// Set the length of the data file, write the decrypted data to it.
m_file.SetLength(dwDataLength);
m_file.Write(pData, dwDataLength);
m_file.Flush();
m_file.SeekToBegin();
// Free the memory we release from the memory file.
delete [] pData;
return true;
}