CryptImportKey fails on Windows 8

321 Views Asked by At

Using Crypto32 Windows, function CryptoImportKey fails on Windows 8.1 returning ERROR_INVALID_PARAMETER. It worked well with all preceding versions of Windows.

Anyone has some hint for it?

The code is:

if (!CryptAcquireContext(&hProv, NULL, MS_DEF_PROV, PROV_RSA_FULL, 0))
{
    dwResult = GetLastError();
    if (dwResult == NTE_BAD_KEYSET)
    {

        if (!CryptAcquireContext(&hProv, NULL, MS_DEF_PROV, PROV_RSA_FULL, CRYPT_NEWKEYSET))
        {
            dwResult = GetLastError();
            strAux.Format("Error [%x]: CryptAcquireContext() failed.",dwResult);
            AfxMessageBox(  strAux,  MB_OK);
            return;
        }
    } else {
        dwResult = GetLastError();
        strAux.Format("Error [0x%x]: CryptAcquireContext() SECOND failed.",dwResult);
        AfxMessageBox(  strAux,  MB_OK);
        return;
    }
}

if (pbBlob != NULL)
{  
    //Porto 02-07-2014
    *(DWORD *)(pbBlob + 0x14) = 0; // Set the packed key length to zero 

    if (!CryptImportKey(hProv, pbBlob, cbBlob, 0, 0, &hSessionKey))
    {
        dwResult = GetLastError();
        strAux.Format("Error [%x]: CryptImportKey() failed.Size: %d",dwResult,cbBlob);
        AfxMessageBox(  strAux,  MB_OK);
        return;
    }
} else { 
    if (!CryptImportKey(hProv, PrivateKeyWithExponentOfOne, sizeof(PrivateKeyWithExponentOfOne), 0, 0, &hKey))
    {
        strAux.Format("Error [%x]: CryptImportKey() PRIVATE failed.",dwResult);
        AfxMessageBox(  strAux,  MB_OK);
        return;
    }
1

There are 1 best solutions below

1
On

There is a bug as described here. Keys exported from Windows 7 cannot be imported into Windows 8.1.

That blog post describes a workaround. In the OPAQUEKEYBLOB, set the DWORD at offset 0x14 to zero:

*(DWORD *)(lpBlob + 0x14) = 0; // Set the packed key length to zero 

This allows a Windows 7 key to be imported into Windows 8.1.