[openssl-users] C++ How to parse Subject Directory Attributes Extension?

Dr. Stephen Henson steve at openssl.org
Tue May 9 16:05:45 UTC 2017

On Tue, May 09, 2017, Matthias Ballreich wrote:

> Here are nor some more details, which may help you to better understand.
> My Certificate contains the SubjectDirectoryAttributes-Extension with the following Attributes:
> OID                                       : Value
> -------------------------------------------------------------------
> ( countryOfCitizenship  : DE
> ( gender                : F
> ( dateOfBirth           : 1971-10-14 12:00:00 UTC
> ( placeOfBirth          : Darmstadt
> So i want to get these pairs of OID and Value.
> I found no Struct like SUBJECT_DIRECTORY_ATTRIBUTES in the Source-Code i can use. I got the Extension this way:
> int loc = X509_get_ext_by_NID(certificate, NID_subject_directory_attributes, -1);
> X509_EXTENSION *ex = X509_get_ext(certificate, loc);
> But how can i get then all the data, which means all the OIDs and Values to the OIDs? The ASN.1 Structure is:
> SubjectDirectoryAttributes ::= Attributes
> Attributes ::= SEQUENCE SIZE (1..MAX) OF Attribute
> Attribute ::= SEQUENCE
> {
>     type AttributeType
>     values SET OF AttributeValue
> }
> AttributeType ::= OBJECT IDENTIFIER
> AttributeValue ::= ANY DEFINED BY AttributeType
> I found out that i get a custom extension with: X509_EXTENSION_get_object(ex) and that the OpenSSL-Type X509_NAME_ENTRY is the equvivalent to the ASN.1-Structure Attribute resp. AttributeTypeAndValue. So i tried to cast the result of X509_EXTENSION_get_data(ex) to a STACK_OF(X509_NAME_ENTRY) and to X509_NAME. But X509_NAME is the same as STACK_OF(X509_NAME_ENTRY).
> Then i tried to get the number of attributes by calling the sk_X509_NAME_ENTRY_num() function on the STACK_OF(X509_NAME_ENTRY) resp. X509_NAME.entries, but i got not the right number. I expect to get the number 3 or 4 (don't know the exactly internal counting - but the example cert contains 4 Attributes, so the output should be 3 or 4 depending if the counting will start at 0 or 1). But instead of 3 or 4 i got a much larger number like 34335029 and this number is different every time i run the code. So i think there is a problem with the casting or i did not choose the right Data-Type(s).
> I'm using OpenSSL 1.0.2j.
> So what's wrong and how can i fix it? - Thanks in advice!

Looks like the type isn't X509_NAME_ENTRY but X509_ATTRIBUTE and the extension
is a SEQUENCE OF Attribute. We don't have the direct equivalent as a specific
type IIRC but it isn't hard to add one just follow what is done for

You can either add a custom extension or just parse the structure from the
extentsion contents.

Dr Stephen N. Henson. OpenSSL project core developer.
Commercial tech support now available see: http://www.openssl.org

More information about the openssl-users mailing list