Our DNA is written in Swift

Parsing ASN.1 for Certificates and Pleasure

When figuring out how to work with self-signed certificates and helping somebody debug an SSL problem I did a bit of research regarding the certificates being used on iOS and what functions are available to inspect these.

There are two functions provided to get more information from a SCCertificateRef , one to get a meager description, the other to get the entire certificate, encoded in ASN.1. But there you’re stuck, unless you want to mess with compiling and installing OpenSSL.


OpenSSL is the de-facto standard method of decoding certificates on Mac. For example you can parse a binary ASN.1-encoded (aka DER) certificate as easy as:

openssl asn1parse -in certi.der
   0:d=0  hl=4 l=1086 cons: SEQUENCE
    4:d=1  hl=4 l= 806 cons: SEQUENCE
    8:d=2  hl=2 l=   3 cons: cont [ 0 ]
   10:d=3  hl=2 l=   1 prim: INTEGER           :02
   13:d=2  hl=2 l=  16 prim: INTEGER           :19D031A4DCCFB1691284E00750BA7A23
   31:d=2  hl=2 l=  13 cons: SEQUENCE
   33:d=3  hl=2 l=   9 prim: OBJECT            :sha1WithRSAEncryption
   44:d=3  hl=2 l=   0 prim: NULL
   46:d=2  hl=2 l=  94 cons: SEQUENCE
   48:d=3  hl=2 l=  11 cons: SET
   50:d=4  hl=2 l=   9 cons: SEQUENCE
   52:d=5  hl=2 l=   3 prim: OBJECT            :countryName
   57:d=5  hl=2 l=   2 prim: PRINTABLESTRING   :US
   61:d=3  hl=2 l=  21 cons: SET
   63:d=4  hl=2 l=  19 cons: SEQUENCE
   65:d=5  hl=2 l=   3 prim: OBJECT            :organizationName
   70:d=5  hl=2 l=  12 prim: PRINTABLESTRING   :Thawte, Inc.

OpenSSL comes preinstalled on all Macs, but we don’t know what it was that Apple did not like about it to omit it on iOS. Was it the “Open”? Was is the license? We will never know.

The above is exactly the same information that Safari shows you if an SSL connection cannot be verified. Wouldn’t it be nice to be able to get this kind of mechanism for our own apps as well? Some clients might want to be able to accept self-signed certificates, but not do so without notice, but rather show all certificate details to the user like Safari does.  With DTASN1Parser this becomes possible.

Another scenario that needs to decode certificates is to validate them, for example to check if the certificate your app is signed with is indeed one for the app store …

I remember – a couple of years ago – I wrote an ASN.1 Decoder and Encoder in C++, but those backups were lost in time. So I scraped together in information about the format what I could find. Unfortunately it is just as cryptic as the cryptography that is is used for in our case.

I found and borrowed ideas from two web-based decoders (1, 2), skimmed through a “Layman’s Guide“,  marveled at The Anatomy of a X.509 Certificate, but then gave up on the mother of all ASN1 tutorials: ASN1 Complete.

Getting the Certificate

If you do an NSURLConnection to a server with a self-signed (or shady) certificate you get a callback for an authentication space. From this you can get the SecTrust and from that you may retrieve the certificates used.

– (void)connection:(NSURLConnection *)connection
didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
if ([challenge.protectionSpace.authenticationMethod
SecTrustRef secTrust = [challenge.protectionSpace serverTrust];

SecCertificateRef certi = SecTrustGetCertificateAtIndex(secTrust, 0);
NSData *data = (__bridge_transfer NSData *) SecCertificateCopyData(certi);
// .. we have a certificate in DER format!

NSString *summ = (__bridge_transfer NSString *) SecCertificateCopySubjectSummary(certi);
// … a useless summary

I saved a certificate to disk with this method and – lo and behold! – you can inspect the certificate with QuickLook.

That’s quite convenient, because you have a direct comparison with what data we can decode with DTASN1Parser.

DTASN1Parser walks through the hierarchy contained within the ASN.1 data and emits events whenever it encounters something noteworthy. To build a certificate class with it you would create a parser with the data and then act on the individual events. Here’s the basic structure:

@implementation DTCertificate
	NSData *_data;
	id _rootContainer;
	id _currentContainer;
	NSMutableArray *_stack;
	NSString *currentObjectIdentifier;
	DTASN1Parser *_parser;
- (id)initWithData:(NSData *)data
	self = [super init];
	if (self)
		_parser = [[DTASN1Parser alloc] initWithData:data];
		_parser.delegate = self;
		_stack = [[NSMutableArray alloc] init];
		if (![_parser parse])
			return nil;
	return self;
#pragma mark DTASN1ParserDelegate
- (void)parser:(DTASN1Parser *)parser foundObjectIdentifier:(NSString *)objIdentifier
	currentObjectIdentifier = objIdentifier;
- (void)parser:(DTASN1Parser *)parser didStartContainerWithType:(DTASN1Type)type
	// start a new container
	id previousContainer = _currentContainer;
	// we don't care about the sequences, just the structure
	_currentContainer = [[NSMutableArray alloc] init];
	currentObjectIdentifier = nil;
	[previousContainer addObject:_currentContainer];
	if (!_rootContainer)
		_rootContainer = _currentContainer;
	[_stack addObject:_currentContainer];
- (void)parser:(DTASN1Parser *)parser didEndContainerWithType:(DTASN1Type)type
	// remove item from stack
	[_stack removeLastObject];
	_currentContainer = [_stack lastObject];
- (void)addObject:(id)object forIdentifier:(NSString *)identifier
	if (identifier)
		NSDictionary *dict = [NSDictionary dictionaryWithObject:object forKey:identifier];
		NSLog(@"%@", dict);
		[_currentContainer addObject:dict];
		[_currentContainer addObject:object];
		NSLog(@"%@", object);
- (void)parserFoundNull:(DTASN1Parser *)parser
	[self addObject:[NSNull null] forIdentifier:currentObjectIdentifier];
- (void)parser:(DTASN1Parser *)parser foundDate:(NSDate *)date
	[self addObject:date forIdentifier:currentObjectIdentifier];
- (void)parser:(DTASN1Parser *)parser foundString:(NSString *)string
	[self addObject:string forIdentifier:currentObjectIdentifier];
- (void)parser:(DTASN1Parser *)parser foundData:(NSData *)data
	[self addObject:data forIdentifier:currentObjectIdentifier];
- (void)parser:(DTASN1Parser *)parser foundNumber:(NSNumber *)number
	[self addObject:number forIdentifier:currentObjectIdentifier];

The general method of representing certificate elements in ASN.1 is to have an object identifier and a value for it. Those object identifiers are standardized and often they are represented concatenated with dots. You usually have a SET container, with the first element being an object identifier, followed by a string.

    "" = "US";
    "" = "Thawte, Inc.";
    "" = "Domain Validated SSL";
    "" = "Thawte DV SSL CA";

Here’s a list of the object identifiers you might encounter:,extension,signature

There’s a catch when dealing with bytes. I found that sometimes an element actually consists of sub-elements. For example the 1.2.840.113549.1.1.1 public key data also encodes an exponent field. I was unable to find documentation on how to know that just from the data. One of the JS decoders explodes this field, the other doesn’t. Worst case you’ll have to know which fields do that and parse these out yourself.

Another thing I did not understand is the use of the context fields. Those are represented as [0] and [3] in the JS tools. The must have some meaning, but I couldn’t find it.


With DTASN1Parser (new member of DTFoundation) you can now knock yourself out making nice dialogs giving all the certificate information to your user he needs to be able to know that this certificate is ok to permanently accept. The big advantage of this parser over OpenSSL is that you only have to add two files to your project (or DTFoundation) and don’t need to mess around with getting OpenSSL compiled for iOS.

If you do set out to create such an Accept Certificate dialog, then get in touch, we should collaborate on that.

DTASN1Parser is quite crude, there are many special cases that are not yet implemented, because I didn’t encounter them in working with a DER-encoded certificate. If you have DER-data that makes use of these, then please let me have that for testing … or better yet, implement it in the Open Source project and send me a pull request.

Categories: Projects



  1. RFC: DTCertificateViewer | Cocoanetics
  2. Apple’s ASN.1 OID Names | Cocoanetics

Leave a Comment

%d bloggers like this: