ASN1, also known as ASN.1, or spelled out as Abstract Syntax Notation One, is a method of defining a data structure primarily used in cryptography and for the purposes of this article, we will discuss its use in X.509 digital certificates. ASN1 is used to define the format of certificates in its most basic form.
asn1 encoding
ASN1 is closely related to Basic Encoding Rules (BER), Distinguished Encoding Rules (DER), and Canonical Encoding Rules (CER), all common encoding’s for X.509 certificates.
It is important to grasp that these encoding rules have cross-platform support. While some encodings are used more often on one platform than another, they should in theory be supported on any platform.
For example, the PEM format is the Base 64 ASCII encoding of a DER encoded ASN1 certificate.
asn1 format
As mentioned in the opening paragraph, ASN.1 is used to define the format of X.509 digital certificates.
asn1js
ASN1js is a javascript library for managing and working with BER encoded X.509 certificates in javascript code. It can be used as an ASN1 decoder to read the encoded data.
It can be found here: https://www.npmjs.com/package/asn1js
Here is an example of getting the expiration date from a PEM encoded X.509 certificate using the asn1js library. You will also need the pkijs library, found here: https://www.npmjs.com/package/pkijs
getCertificateExpirationDate() {
const certificate = "YOUR PEM ENCODED CERTIFICATE";
// PEM encoding - replace the header and footer
const b64 = certificate.replace(/(-----(BEGIN|END) CERTIFICATE-----|[\n\r])/g, '');
// Conver to DER encoding
const der = Buffer.from(b64, 'base64');
// Convert to BER encoding
const ber = new Uint8Array(der).buffer;
// Asn1js operations
const asn1 = asn1js.fromBER(ber);
const { Certificate } = pkijs;
const certificate = new Certificate({ schema: asn1.result });
return moment(new Date(certificate.notAfter.value.toString())).format('MM/DD/YYYY').toString();
},
Following through the code demonstrates that the ASN1js library needs the BER encoded certificate to operate from.
Let us know in the comments if you are interested in seeing additional examples of this library.
Using the openssl asn1parse utility.
The openssl asn1parse utility is an asn1 parser that will take an input in a supported encoding, and parse the encoding into the asn1 format.
For example, to parse a PEM encoded X.509 certificate, run the following command:
openssl asn1parse -in example.com.pem
The same command can be used to parse a DER encoded X.509 certificate, just add the following option: -inform DER
Leave a Reply