NCryptOpenKey function (ncrypt.h)

The NCryptOpenKey function opens a key that exists in the specified CNG key storage provider.


  [in]  NCRYPT_PROV_HANDLE hProvider,
  [out] NCRYPT_KEY_HANDLE  *phKey,
  [in]  LPCWSTR            pszKeyName,
  [in]  DWORD              dwLegacyKeySpec,
  [in]  DWORD              dwFlags


[in] hProvider

The handle of the key storage provider to open the key from.

[out] phKey

A pointer to a NCRYPT_KEY_HANDLE variable that receives the key handle. When you have finished using this handle, release it by passing it to the NCryptFreeObject function.

[in] pszKeyName

A pointer to a null-terminated Unicode string that contains the name of the key to retrieve.

[in] dwLegacyKeySpec

A legacy identifier that specifies the type of key. This can be one of the following values.

Value Meaning
The key is a key exchange key.
The key is a signature key.
The key is none of the above types.

[in] dwFlags

Flags that modify function behavior. This can be zero or a combination of one or more of the following values.

Value Meaning
Open the key for the local computer. If this flag is not present, the current user key is opened.
Requests that the key service provider (KSP) not display any user interface. If the provider must display the UI to operate, the call fails and the KSP should set the NTE_SILENT_CONTEXT error code as the last error.

Return value

Returns a status code that indicates the success or failure of the function.

Possible return codes include, but are not limited to, the following.

Return code Description
The function was successful.
The dwFlags parameter contains a value that is not valid.
The specified key was not found.
The hProvider parameter is not valid.
One or more parameters are not valid.
A memory allocation failure occurred.


A service must not call this function from its StartService Function. If a service calls this function from its StartService function, a deadlock can occur, and the service may stop responding.

For performance reasons, Microsoft software-based KSPs cache private key material in the Local Security Authority (LSA) for as long as a handle to the key is open. The LSA is a privileged system process. Therefore, other users cannot access this cached copy of the key unless the user possesses administrator privileges on the system. This behavior cannot be altered through configuration.


Minimum supported client Windows Vista [desktop apps | UWP apps]
Minimum supported server Windows Server 2008 [desktop apps | UWP apps]
Target Platform Windows
Header ncrypt.h
Library Ncrypt.lib
DLL Ncrypt.dll