The CryptDuplicateKey function is used to make an exact copy of a key and the state the key is in. Some keys have an associated state, for example an initialization vector and/or a salt value.
#include <wincrypt.h>
BOOL WINAPI CryptDuplicateKey(
HCRYPTKEY hKey, // in
DWORD *pdwReserved, // in
DWORD dwFlags, // in
HCRYPTKEY* phKey // out
);
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_CALL_NOT_IMPLEMENTED | Since this is a new function, existing CSPs may not implement it. This error is returned if the CSP does not support this function. |
ERROR_INVALID_PARAMETER | One of the parameters contains an invalid value. This is most often an illegal pointer. |
NTE_BAD_KEY | The handle to the original key is not valid. |
CryptDuplicateKey is used to make copies of keys and the exact state of the key. An example of how this function might be used is that a caller may want to encrypt two separate messages with the same key, but with different salt values. The key could be generated, a duplicate would be made with the CryptDuplicateKey function, and then the appropriate salt value would be set on each key with the CryptSetKeyParam function.
CryptDestroyKey must be called to destroy any keys that are created with CryptDuplicateKey. Destroying the original key does not cause the duplicate key to be destroyed. Once a duplicate key is made, it is separate from the original key. There is no shared state between the two keys.
HCRYPTPROV hProv = 0;
HCRYPTKEY hOriginalKey = 0;
HCRYPTKEY hDuplicateKey = 0;
DWORD dwErr;
// Generate a key.
if (!CryptGenKey(hProv, CALG_RC4, 0, &hOriginalKey))
{printf("ERROR - CryptGenKey: %X\n", GetLastError());
return;}
// Duplicate the key.
if (!CryptDuplicateKey(hOriginalKey, NULL, 0, &hDuplicateKey))
{printf("ERROR - CryptDuplicateKey: %X\n", GetLastError());
return;}
...
// Destroy the original key.
if (!CryptDestroyKey(hOriginalKey))
{printf("ERROR - CryptDestroyKey: %X\n", GetLastError());
return;}
// Destroy the duplicate key.
if (!CryptDestroyKey(hDuplicateKey))
{printf("ERROR - CryptDestroyKey: %X\n", GetLastError());
return;}
Windows NT: Requires version 5.0 or later.
Windows: Unsupported.
Windows CE: Unsupported.
Header: Declared in wincrypt.h.
Import Library: Use advapi32.lib.