CryptDestroyKey

The CryptDestroyKey function releases the handle referenced by the hKey parameter. After a key handle has been released, it becomes invalid and cannot be used again.

If the handle refers to a session key, or to a public key that has been imported into the CSP through CryptImportKey, this function destroys the key and frees the memory that the key occupied. Many CSPs will scrub the memory where the key was held before freeing it.

On the other hand, if the handle refers to a public/private key pair (obtained from CryptGetUserKey), the underlying key pair is not destroyed by this function. Only the handle is destroyed.

#include <wincrypt.h>
BOOL WINAPI CryptDestroyKey(
  HCRYPTKEY hKey     // in
);
 

Parameters

hKey
Handle to the key to be destroyed.

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 The hKey parameter specifies an invalid handle.
ERROR_INVALID_PARAMETER The hKey parameter contains an invalid value.
NTE_BAD_KEY The hKey parameter does not contain a valid handle to a key.
NTE_BAD_UID The CSP context that was specified when the key was created cannot be found.

Remarks

Keys take up memory in both the operating system's memory space and the CSP's memory space. Some CSPs will be implemented in hardware with very limited memory resources. For this reason, it is important that applications destroy all keys with the CryptDestroyKey function when they are finished with them.

Example

See CryptHashSessionKey.

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

CryptDeriveKey, CryptGenKey, CryptGetUserKey, CryptImportKey