I’ve just finished up writing some OpenSSL/PKCS7 digital signature code and now have a working PEM encoded PKCS7 file. So after little battle, I need to convert that PEM to DER format. This is proving tougher than I hoped.
There are some convenience methods in OpenSSL such as “PEM_write_bio_PKCS7_stream” to write your PKCS7 object. But after some extensive googling and browsing some header files, I can’t seem to find anything to take a PKCS7 object and write it to anything (BIO, FILE, char*) in DER format.
So feeling defeated there, I turned to parsing out the header & footer in the PEM file and Base64 decoding the contents. As a check, I did this with Java & BouncyCastle and got exactly what I want.
Here’s my code for that. With almost every Base64 decoder I try I turn something like this…
MIIHmwYJKoZIhvcNAQcCoIIHjDCCB4gCAQExCzAJBgUrDgMCGgUAMIIBrQYJKoZI
hvcNAQc ... Lots More stuff
... +8L5ad45D/7ZGJWafaSw==
into…
0\202\233 *\367\367
\240\202\2140\202\21010 +
Here’s that code…
string PKCS7String(starting_point);
string PEM_PKCS7_HEADER("-----BEGIN PKCS7-----\n");
string PEM_PKCS7_FOOTER("\n-----END PKCS7-----");
string::size_type pos = 0;
while ( (pos = PKCS7String.find(PEM_PKCS7_HEADER, pos)) != string::npos ) {
PKCS7String.replace( pos, PEM_PKCS7_HEADER.length(), "" );
pos++;
}
pos = 0;
while ( (pos = PKCS7String.find(PEM_PKCS7_FOOTER, pos)) != string::npos ) {
PKCS7String.replace( pos, PEM_PKCS7_FOOTER.length(), "" );
pos++;
}
//Take your pick of decoders, they all do the same thing. Here's just the most recent
auto_ptr< uint8_t > decoded = decode(PKCS7String);
uint8_t* array = decoded.get();
cout << array << endl;
Any thoughts?
i2d_PKCS7_fp()andi2d_PKCS7_bio()from<openssl/pkcs7.h>will write out aPKCS7structure in DER format to a file stream or BIO respectively.