In the original Base Provider, 40-bit symmetric keys were used exclusively. The addition of longer keys in the Enhanced Provider, and the fact that imported keys can be of arbitrary length, precipitates the need for a method of querying the length for a specific key. The following parameter value is provided for both providers to determine a key's length.
To get the actual length of a key in bits, a user can call CryptGetKeyParam with the KP_KEYLEN parameter value. The length of the key is located in the DWORD pointed to by pbData.
Note that it is desirable for applications to use the KP_KEYLEN parameter value to check for insufficient key lengths and notify the user when one is encountered. This protects against stepping-down attacks.
The following example shows how to query the length of a key.
// Example using CryptGetKeyParam with the KP_KEYLEN parameter value.
// [...] Assume an acquired context.
DWORD dwKeyLength;
DWORD dwLen=sizeof(DWORD);
// Generate a key.
if (!CryptGenKey(
hDefProv,
CALG_RC2,
0,
&hKey))
goto Ret;
// Query the key length.
if (!CryptGetKeyParam(
hKey,
KP_KEYLEN,
(BYTE*)&dwKeyLength,
&dwLen,
0))
goto Ret;
if (!CryptDestroyKey(hKey))
goto Ret;
printf("The RC2 key generated is %d bits long\n", dwKeyLength);
// [...] Assume a released context.