Microsoft, a few years ago, wrote a new cryptography API for Windows Vista called Cryptography Next Generation (CNG). This replaces the existing cryptography API in Windows XP and earlier versions which was simply called CryptoAPI.
Now, compatibility between the two APIs is touted as a feature of the new CNG API, but a somewhat more sombre reality tends to set in pretty quickly once you start working with them. A motley collection of loosely documented data structures, endianness differences, and “Not Supported” footnotes pile up as quickly as you can open MSDN documentation tabs in your browser. In my research, I also found a dearth of concrete examples of how to interoperate between the two APIs online. In fact, there was only one page which really helped, buried in Microsoft’s Output Protection Manager documentation.
There is something magical about all your bits lining up in a row when mixing crypto libraries of any ilk, and I wanted to share! Hence this story.
My requirement was pretty simple: I wanted to generate an RSA key pair using CryptoAPI in my client application, hand off the public key to another application, which happens to use CNG, wave my hands a little, and magically transact a key exchange. Here’s how to do it (with some error handling elided for your own reading sanity). You should be able to load this into any recent version of Visual Studio, add bcrypt.lib to your library includes and build. The code should be reasonably self-explanatory, so I’ll leave it there.
The usual disclaimers apply. Source on GitHub.