Search code examples
copensslx509

Openssl: Convert Distinguished Name from String to DER encoding


I have the issuer of a X.509 certificate as a string representation:

"C=UT/O=foobar/OU=foo/serialNumber=0123/CN=TEST ca"

How can I get the Distinguished Name elements from a String representation to a DER encoded form (with their respective OIDs) with openssl in C.


Solution

  • i2d_X509_NAME is function for converting openSSL X509_NAME* object to DER format.

    I don't know is there function to convert whole "C=UT/O=foobar/OU=foo/serialNumber=0123/CN=TEST ca" string to X509_NAME* directly.

    But maybe simple (error checkings are missing for simplicity) example helps:

    #include <stdlib.h>
    #include <stdio.h>
    #include <unistd.h>
    #include <openssl/pem.h>
    
    int main()
    {   
        unsigned char *buffer = NULL;
        X509_NAME *name = X509_NAME_new();
    
        X509_NAME_add_entry_by_txt(name, "O",  MBSTRING_UTF8, 
                                   (unsigned char*)"Organization", -1, -1, 0);
        X509_NAME_add_entry_by_txt(name, "CN",  MBSTRING_UTF8, 
                                   (unsigned char*)"MyName", -1, -1, 0 );
        
        int len = i2d_X509_NAME(name, &buffer);     
        fwrite(buffer, len, 1, stdout);
        OPENSSL_free(buffer);
        X509_NAME_free(name);
            
        return EXIT_SUCCESS;
    }
    

    Test:

    $ gcc x509_name.c -Wall -o x509_name -lcrypto
    $ ./x509_name | hexdump -C
    00000000  30 28 31 15 30 13 06 03  55 04 0a 0c 0c 4f 72 67  |0(1.0...U....Org|
    00000010  61 6e 69 7a 61 74 69 6f  6e 31 0f 30 0d 06 03 55  |anization1.0...U|
    00000020  04 03 0c 06 4d 79 4e 61  6d 65                    |....MyName|
    0000002a
    $