Crypto API Encoding

Finally I am getting to the point where I am following the Microsoft Crypto API documentation in order to actually encode some data. But first let’s talk about what you need to get your software to compile and link. You must link in the crypt32.lib library. You may also need access to the advapi32.dll. You C or C++ code must include the wincrypt.h header file. And last you must define MY_ENCODING_TYPE in your code.

Now let’s get down to business. Here is the pattern you will follow to encode data. You start by calling the cryptmsgopentoencode function. Then you call cryptmsgupdate as many times as you have data to add. On the last data addition, you call cryptmsgupdate with the fFinal parameter set to true. To end the encoding, you call the cryptmsgclose function. These are the basics in a nutshell.

The algorithm to decode data mimics the one to encode. There is one extra step in the beginning where you call the cryptmsgcalculateencodedlength function. Then you call the cryptmsgopentodecode function. Does that sound familiar? You call the cryptmsgupdate function. And you end by calling the cryptmsgclose function.

Since we are down to the details of actual coding here, I also have the algorithms to encrypt and decrypt data. Perhaps I will share that with you in my next post. For now I will leave you with the concept of enveloping data. This is where you would like to encrypt a message for a whole set of recipients. You encrypt the message with a key. Then you in turn encrypt that key for each of the recipients on your distribution list for the message. The encryption is done in PKCS 7 format. Each recipient can then decrypt their key, and subsequently decrypt the message.