The other day I found out about CryptBinaryToString for the first time, and I was very pleasantly surprised.
First, because it means I can stop reaching for a whole bunch of ATL stuff every time I want a simple base64 encoding. Don't get me wrong, there is plenty of awesome functionality in the ATL Text Encoding Functions, but sometimes it gets messy to pull in ATL.
Second, crypt32.dll has been around for a while now, and it's hard to imagine it going anywhere.
A big question I had, however, was how the various flags might look like. Enter today's little program.
#include <windows.h>
#include <wincrypt.h>
#include <stdio.h>
#pragma comment(lib,"Crypt32.lib")
int main() {
const BYTE binary[] = { 'a', 'b', 'c', 'd' };
struct Flag {
const char *name;
DWORD value;
};
const Flag flags[] = {
{ "BASE64HEADER", CRYPT_STRING_BASE64HEADER },
{ "BASE64", CRYPT_STRING_BASE64 },
{ "BINARY", CRYPT_STRING_BINARY },
{ "BASE64REQUESTHEADER", CRYPT_STRING_BASE64REQUESTHEADER },
{ "HEX", CRYPT_STRING_HEX },
{ "HEXASCII", CRYPT_STRING_HEXASCII },
{ "BASE64X509CRLHEADER", CRYPT_STRING_BASE64X509CRLHEADER },
{ "HEXADDR", CRYPT_STRING_HEXADDR },
{ "HEXASCIIADDR", CRYPT_STRING_HEXASCIIADDR },
{ "HEXRAW", CRYPT_STRING_HEXRAW }
};
char str[1024];
for (size_t i = 0; i < _countof(flags); ++i) {
const Flag& flag = flags[i];
DWORD strcount = _countof(str);
CryptBinaryToStringA(binary, _countof(binary), flag.value, str, &strcount);
printf("flag %s produces:\n%s\n", flag.name, str);
}
return 0;
}
If you start up a Developer Command prompt and build with cl ct.cpp
, you can then run ct.exe
and get this output.
flag BASE64HEADER produces:
-----BEGIN CERTIFICATE-----
YWJjZA==
-----END CERTIFICATE-----
flag BASE64 produces:
YWJjZA==
flag BINARY produces:
abcdZA==
flag BASE64REQUESTHEADER produces:
-----BEGIN NEW CERTIFICATE REQUEST-----
YWJjZA==
-----END NEW CERTIFICATE REQUEST-----
flag HEX produces:
61 62 63 64
flag HEXASCII produces:
61 62 63 64 abcd
flag BASE64X509CRLHEADER produces:
-----BEGIN X509 CRL-----
YWJjZA==
-----END X509 CRL-----
flag HEXADDR produces:
0000 61 62 63 64
flag HEXASCIIADDR produces:
0000 61 62 63 64 abcd
flag HEXRAW produces:
61626364
Enjoy!
Tags: crypto