开发者

PEM Conversion (PKCS7) to DER - AKA Base64 C++ Problems

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?


A PEM file is just a Base64 encoded version of the DER file with the -----BEGIN PKCS7----- & -----END PKCS7----- header and footer lines.
So not exactly sure what you expect to see after Base64 decoding it...

As a test just:

  1. package a certificate in PKCS#7 PEM format: $ openssl crl2pkcs7 -nocrl -out outfile.pem.p7b -certfile server.crt -outform pem

  2. package the same certificate in PKCS#7 DER format: $ openssl crl2pkcs7 -nocrl -out outfile.der.p7b -certfile server.crt -outform der

  3. Base64 decode the body of the PEM file (outfile.pem.p7b) with the decoder of your choice & compare the binary output with the DER file (outfile.der.p7b)

Now, I'm afraid this may be what you asked for but not what you wanted...


i2d_PKCS7_fp() and i2d_PKCS7_bio() from <openssl/pkcs7.h> will write out a PKCS7 structure in DER format to a file stream or BIO respectively.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜