CryptGetUserKey

The CryptGetUserKey function retrieves a handle to a permanent user key pair, such as the user's signature key pair.

#include <wincrypt.h>
BOOL WINAPI CryptGetUserKey(
  HCRYPTPROV hProv,      // in
  DWORD dwKeySpec,       // in
  HCRYPTKEY *phUserKey   // out
);
 

Parameters

hProv
A handle to the application's CSP. An application obtains this handle by using the CryptAcquireContext function.
dwKeySpec
The specification of the key to retrieve. The following keys are retrievable from almost all providers:

Additionally, some providers allow access to other user-specific keys through this function. See the documentation on the specific provider for details.

phUserKey
The address that the function copies the handle of the retrieved key to.

Return Values

If the function succeeds, the return value is TRUE. If it fails, the return value is FALSE. To retrieve extended error information, use the GetLastError function.

The following table lists the error codes most commonly returned by the GetLastError function. The error codes prefaced by "NTE" are generated by the particular CSP you are using.

Error code Description
ERROR_INVALID_HANDLE One of the parameters specifies an invalid handle.
ERROR_INVALID_PARAMETER One of the parameters contains an invalid value. This is most often an illegal pointer.
NTE_BAD_KEY The dwKeySpec parameter contains an invalid value.
NTE_BAD_UID The hProv parameter does not contain a valid context handle.
NTE_NO_KEY The key requested by the dwKeySpec parameter does not exist.

Example

#include <wincrypt.h>

HCRYPTPROV hProv = 0;
HCRYPTKEY hSignKey = 0;
HCRYPTKEY hXchgKey = 0;

// Get a handle to the user default provider.
if(!CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, 0)) {
    printf("Error %x during CryptAcquireContext!\n", GetLastError());
    goto done;
}

// Get a handle to the signature key.
if(!CryptGetUserKey(hProv, AT_SIGNATURE, &hSignKey)) {
    printf("Error %x during CryptGetUserKey!\n", GetLastError());
    goto done;
}

// Get a handle to the key exchange key.
if(!CryptGetUserKey(hProv, AT_KEYEXCHANGE, &hXchgKey)) {
    printf("Error %x during CryptGetUserKey!\n", GetLastError());
    goto done;
}

// Use the  'hSignKey' to verify a signature, or use 'hXchgKey' to export a key to yourself.
...

done:

// Destroy the signature key handle.
if(hSignKey != 0) CryptDestroyKey(hSignKey);

// Destroy the key exchange key handle.
if(hXchgKey != 0) CryptDestroyKey(hXchgKey);

// Release the provider handle.
if(hProv != 0) CryptReleaseContext(hProv, 0);
 

Another example is located in Encryption Example.

QuickInfo

  Windows NT: Requires version 4.0 or later.
  Windows: Requires Windows 95 OSR2 or later (or Windows 95 with IE 3.02 or later).
  Windows CE: Unsupported.
  Header: Declared in wincrypt.h.
  Import Library: Use advapi32.lib.

See Also

CryptAcquireContext, CryptDestroyKey, CryptGenKey