0

I am using blob in my encryption application to store the encryption key.

I am a beginner in MFC. I am using CryptExportKey() to export key to the blob. I have put the below code in my Encrypt() function. See the code in the Encrypt() function below,

if (CryptGetUserKey(
    m_hCryptProv,
    AT_KEYEXCHANGE,
    &hXchgKey))
{
    printf("The key exchange key has been acquired. \n");
}
else
{
    printf("Error during CryptGetUserKey exchange key.");
}

if (CryptExportKey(
    m_hKey,
    hXchgKey,
    SIMPLEBLOB,
    0,
    NULL,
    &dwBlobLen))
{
    _tprintf(
        TEXT("The key BLOB is %d bytes long. \n"),
        dwBlobLen);

}

if (pbKeyBlob = (BYTE*)malloc(dwBlobLen))
{
    printf("Memory has been allocated for the BLOB. \n");
}

if (CryptExportKey(
    m_hKey,
    hXchgKey,
    SIMPLEBLOB,
    0,
    pbKeyBlob,
    &dwBlobLen))
{
    printf("Contents have been written to the BLOB. \n");
}

Also I have put the below code in Decrypt() function to import the key.

    if (!CryptImportKey(
    m_hCryptProv,
    pbKeyBlob,
    dwBlobLen,
    0,
    0,
    &m_hKey))
{
    //success
}

The exporting succeeded but importing failed.

My file will be closed after encryption. When loading the application, the decryption also fails since key is not successfully imported. During encryption and decryption the m_hCryptProv have different values. Is it significant in this case? I am working so longer on this encryption work. Any help appreciated.

Prasanth
  • 75
  • 8

1 Answers1

0

You are using exchange key when export key, so you get a blob encrypted with a hXchgKey. During import you also need specify exchange key to decrypt blob:

if (!CryptImportKey(
    m_hCryptProv,
    pbKeyBlob,
    dwBlobLen,
    hXchgKey,
    0,
    &m_hKey))
{
    //success
}

From MSDN:

BOOL CryptImportKey(
  HCRYPTPROV hProv,
  const BYTE *pbData,
  DWORD      dwDataLen,
  HCRYPTKEY  hPubKey,
  DWORD      dwFlags,
  HCRYPTKEY  *phKey
);

hPubKey:
If the key BLOB is encrypted with the key exchange key pair, for example, a SIMPLEBLOB, this parameter can be the handle to the key exchange key.

plstryagain
  • 686
  • 5
  • 9
  • I am getting m_hkey as 0. I think we need to use same m_hCryptProv and exchange key for both encryption and decryption. Am I right? I am getting different values for m_hCryptProv. – Prasanth Feb 01 '19 at 07:06
  • Yes, you need to use same CSP and exchange key for enc/dec. m_hCryptProv has different value because this is a pointer. – plstryagain Feb 01 '19 at 08:38