Cryptography for Developers

Implementation

Now we will consider how to implement ASN.1 encoders and decoders. Fortunately, most ASN.1 types are primitive and fairly simple to process. The constructed types are slightly harder to develop if the intent is to have a user-friendly API. In our case, we re going to strive for maximum effort while writing the ASN.1 routines such that the resulting code has the maximal amount of use.

All of the ASN.1 routines are found in the ch2 directory of the source code repository. There is a collection of C source files, a single H header file to gather up the prototypes, and a GNU Makefile that will build the collection into an archive using GCC.

The first routines we examine deal with getting, reading, and encoding the length of ASN.1 encodings. The logic is shared by all other ASN.1 types, and as such, makes sense to re-use the code where possible.

ASN.1 Length Routines

The first routine simply returns the length of an encoding, including the header, length bytes, and payload.

der_length.c:001   #include  asn1.h"002   unsigned long der_length(unsigned long payload)003   { 004      unsigned long x;005006      if (payload > 127) { 007         x = payload;008         while (x) { 009           x >>= 8;010           ++payload;011         } 012      } 013014      return payload + 2;015   } 

The function accepts as input the payload length and returns the size of the eventual encoding. This function is suitable for all types where the payload length is known in advance; that is, primitive (nonconstructed) types. Note that for the BIT STRING type the calling function will have to add in the padding counter byte to the payload length for this to work.

This function is useful for encoders, as it allows the caller...

UNLIMITED FREE
ACCESS
TO THE WORLD'S BEST IDEAS

SUBMIT
Already a GlobalSpec user? Log in.

This is embarrasing...

An error occurred while processing the form. Please try again in a few minutes.

Customize Your GlobalSpec Experience

Category: RFID Software
Finish!
Privacy Policy

This is embarrasing...

An error occurred while processing the form. Please try again in a few minutes.