CryptGetUserKey

This function retrieves a handle to a permanent user key pair, such as the user's signature key pair. This function also retrieves a handle to one of a user's two public/private key pairs. Only the owner of the public/private key pairs uses the function and only when the handle to a cryptographic service provider (CSP) and its associated key container is available. Use the CryptAcquireCertificatePrivateKey function if the user's certificate is available, but not the CSP handle.

BOOL WINAPI CryptGetUserKey( HCRYPTPROVhProv,DWORDdwKeySpec,HCRYPTKEY* phUserKey);

Parameters

  • hProv
    [in] HCRYPTPROV handle to a CSP created by a call to CryptAcquireContext.

  • dwKeySpec
    [in] Specifies the key to retrieve. The following keys are retrievable from almost all providers:

    • AT_KEYEXCHANGE.
    • AT_SIGNATURE.

    Additionally, some providers allow access to other user-specific keys through this function.

  • phUserKey
    [out] Pointer to the HCRYPTKEY handle to the retrieved keys.

Return Values

TRUE indicates success. FALSE indicates failure. To get extended error information, call the GetLastError function.

The following table shows the common values for the GetLastError function. The error values prefaced by NTE are generated by the particular CSP you are using.

Value 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 Code

#include <wincrypt.h>

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

// Get a handle to the user default provider.
// Call CryptAcquireContext. For sample code, see CryptAcquireContext.

// 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);
 

Requirements

OS Versions: Windows CE 2.10 and later.
Header: Wincrypt.h.
Link Library: Coredll.lib.

See Also

CryptAcquireContext | CryptDestroyKey | CryptGenKey

 Last updated on Thursday, April 08, 2004

© 1992-2003 Microsoft Corporation. All rights reserved.