5.26. Creating a CryptoAPI Key Object from Raw Key Data
Problem
You have a symmetric key from another API, such as OpenSSL, that you would like to use with CryptoAPI. Therefore, you must create a CryptoAPI key object with the key data.
Solution
The Microsoft CryptoAPI is designed to prevent unintentional disclosure of sensitive key information. To do this, key information is stored in opaque data objects by the Cryptographic Service Provider (CSP) used to create the key object. Key data is exportable from key objects, but the data must be encrypted with another key to prevent accidental disclosure of the raw key data.
Discussion
In Recipe 5.25, we created a convenience function,
SpcGetCryptContext(
)
, for obtaining a handle to a CSP context
object. This function uses the CRYPT_VERIFYCONTEXT
flag with the underlying CryptAcquireContext(
)
function, which serves to prevent the use of
private keys with the obtained context object. To be able to import
and export symmetric encryption keys, you need to obtain a handle to
a CSP context object without that flag, and use that CSP context
object for creating the keys you wish to use. We’ll
create a new function called SpcGetExportableContext(
)
that will return a CSP context object
suitable for creating, importing, and exporting symmetric encryption
keys.
#include <windows.h> #include <wincrypt.h> HCRYPTPROV SpcGetExportableContext(void) { HCRYPTPROV hProvider; if (!CryptAcquireContext(&hProvider, 0, MS_ENHANCED_PROV, PROV_RSA_FULL, 0)) { ...
Get Secure Programming Cookbook for C and C++ now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.