Processing X.509v3 Certificates and CRLs

This section contains code samples illustrating the use of the cdk::Cert class to process X.509v3 certificates. The following examples are provided:

The certificates and CRLs in all of the examples below are represented as base64-encoded octet strings so that they could be included as string literals in the source code. If you are loading a certificate and/or CRL from a file and are unsure whether the data is base64-encoded or not, you should test for the encoding wrapper and, if one is present, remove it before attempting to load the data.

To decode a possibly base64-encoded PDU stored in a cdk::str object x, use a statement of the form:
    if(x[0]!=0x30) x = x.tobin64()
as shown below. (Note that the predicate (x[0]!=0x30) is true when the PDU begins with the character 'M' as it does when it is base64-encoded, whereas all binary ASN.1 encoded PDUs under consideration here start with the tag '\x30' for an ASN.1 BER- or DER-encoded SEQUENCE.)

Parsing Certificates

To parse an X.509v3 certificate, you must first load it into a cdk::Cert object as illustrated in the first example below. Subsequent examples show how to process various certificate components.

Loading a Certificate

In this sample a base64-encoded certificate is decoded and then loaded into a cdk::Cert object.

// put a sample base64-encoded X.509 certificate into a CDK string object
cdk::str strCertificate = 

// decode the certificate if it's base64-encoded
if (strCertificate[0] != 0x30) strCertificate = strCertificate.tobin64();

// instantiate a Cert object and load the certificate string
cdk::Cert c1;
c1.load(strCertificate);     // non-zero return value indicates error

Obtaining Keys, Algorithm IDs, and Validity Periods

Once a certificate has been loaded into a cdk::Cert object its component parts can be extracted. Here the subject public key, algorithm ID, and validity period dates are accessed and pretty-printed:

// assume certificate has been loaded into c1 as above
printf("Subject public key: %s\n", c1.subject_pub.tohex().c_str());
printf("Subject algorithm ID: %s\n", c1.subject_oid.tohex().c_str());
printf("notBefore: %f\n", c1.notBefore);
printf("notAfter: %f\n", c1.notAfter);

The main reason to access the subject_oid and subject_pub components of a cdk::Cert object is to load them into a cdk::Key object for key wrapping or signature validation (see Processing ASN.1 Encoded Keys).

Processing Certificate Extensions

Certificate extensions can be processed serially by calling the getext() method as many times as necessary:

// assume certificate has been loaded into c1 as in first example above
for (int j = 0; ; j++)
  cdk::str oid, value;
  int i = c1.getext(j, oid, value);
  if ( (i != 0) && (i != CDK_EXTENSION_CRITICAL) )
    break;     // no more extensions; we're done
    printf("(critical) ");
  printf("Extension OID: %s, Value: %s\n", oid.tohex().c_str(), value.tohex().c_str());

ISC can make available additional code for performing ASN.1 encoding and decoding operations. If you would like this code for processing certificate extensions, please contact us.

Processing Distinguished Names

You can use cdk::parsedname() to convert distinguished names into human readable (ASCII) text, as shown here:

// assume certificate has been loaded into c1 as in first example above
cdk::str strSubjectDN, strIssuerDN;           // output strings

// convert subject and issuer DNs to ASCII text and print them
cdk::parsedname(c1.subject, strSubjectDN, 2); // see function reference for sort order info
cdk::parsedname(c1.issuer, strIssuerDN, 2);

printf("SubjectDN: %s\n", strSubjectDN.c_str());
printf("IssuerDN: %s\n", strIssuerDN.c_str());

Creating A Certificate

The following code shows how to generate an RSA key pair (see RSA Key Generation) and turn its public key into a self-signed certificate.

// generate a 1024-bit RSA key pair based on a 40-byte random seed
cdk::Key k;                              // instantiate a new Key object
k.RSAkeygen(cdk::getrand2(40), 1024);    // non-zero return value indicates error

// build the new tbsCertificate (i.e., the certificate body)
cdk::Cert c;                             // instantiate a new Cert object
c.version = V3;                          // X.509 version 3
c.serial = cdk::num(HASH_SHA(c.subject_pub, 1)); 
                                         // one way to produce a unique serial number
c.issuer_oid = k.asn1parameters(0,1);    // issuer signature algorithm ID
c.issuer = c.subject;                    // issuer DN
c.notBefore = time(NULL);                // validity period
c.notAfter = time(NULL) + 31536000;      // (one year)

cdk::DName dn;                           // create subject DN
dn.cname = "John Doe"; = "XYZ Corp."; = "US"; 
c.subject = dn.toasn1();

c.subject_oid = k.asn1parameters(1,0);   // subject key algorithm ID (RSA)
c.subject_pub = k.asn1public();          // subject public key
cdk::str body = c.makebody();            // ASN.1 encode the body of the certificate

// sign the tbsCertificate to produce a self-signed certificate
cdk::str cert;                           // output buffer for the certificate
cdk::num r;                              // random seed required for DSA/ECDSA, ignored for RSA
if (k.isRSA())
    k.SetPadding(cdk::RSA::pkcs1);       // specify padding mechanism for RSA, or
    PRNG rand;                           // supply random seed if non-deterministic
    r = (num) rand.gens(20);
k.asn1sign(body,r,cert);                 // sign the certificate; non-zero indicates error 

See RFC 3280 for details.

Creating A CRL

Creating a CRL is similar to creating a certificate:

Cert caCert;                       // assume caCert and caKey have already been initalized
Key caKey;
k.hashtype = hSHA1;                // specify desired hash function

//  build the new tbsCertList (i.e., the CRL body)
cdk::CRL c;                        // instantiate a new CRL object
c.oid = caCert.subject_oid;        // one could also use k.asn1parameters(0,1);
c.issuer = caCert.subject;
c.thisUpdate = cdk::timegmt();
c.nextUpdate = cdk::timegmt() + 365.25 * 24 * 60 * 60;

// create list of revoked certificates and reason codes (see below)
cdk::str crllist = "";
crllist += mkCRLEntry("0x0000001", c.thisUpdate, CRL::certificateHold, CRL::reject);
crllist += mkCRLEntry("0x0000002", c.thisUpdate, CRL::cessationOfOperation);
crllist += mkCRLEntry("0x0000003", c.thisUpdate);
c.list = crllist;

// gather together desired extensions (see below)
cdk::str crlexts = "";
crlexts += asn1::mkAuthKeyIDExt(caCert);  // required for conformance with RFC 3280
crlexts += asn1::mkCRLNumberExt(2163);
c.extra = crlexts;

cdk::str body = c.makebody();      // put it all together as a tbsCertList

// sign the body to produce the CRL
cdk::str crl;                      // output buffer for the CRL
cdk::num r;                        // random seed required for DSA/ECDSA, ignored for RSA
if (k.isRSA())
  k.SetPadding(cdk::RSA::pkcs1); // specify padding mechanism for RSA, or
  PRNG rand;                     // supply random seed if non-deterministic
  r = (num) rand.gens(20);
k.asn1sign(body,r,crl);            // sign the CRL; non-zero indicates error

The following auxiliary function can be used to create the individual entries in the certificate revocation list (i.e., the items in the sequence of revokedCertificates):

cdk::str mkCRLEntry(const cdk::str &serialno, cdk::TimeT revdate, CRL::Reasons reason, 
  CRL::Instructions instruction)
  str x,y = "";
  cdk::TimeT t = revdate; // cdkdatetounix(revdate);
  num serial(hex(serialno));
  x = asn::integer(serial) + asn::date(t);
  if ( reason == 6 && instruction > 0 )   
    cdk::str strIns = "";
    switch (instruction)
    case CRL::callissuer:
      strIns = Obj*CRL_hold_callissuer;
    case CRL::reject:
      strIns = Obj*CRL_hold_reject;
    case CRL::pickuptoken:
      strIns = Obj*CRL_hold_pickuptoken;
    case none:
      strIns = Obj*CRL_hold_none;
    y = Seq*(Obj*id_ce_holdInstructionCode+Oct*(strIns));
  if ( reason >= 0 ) x += Seq& Seq*(Obj*id_ce_cRLReasons+Oct*(x0A*single(reason))) + y;
  return Seq*x;

while the following functions can be used to create the extensions:

cdk::str mkAuthKeyIDExt(const cdk::Cert &cert)
  // compute SHA-1 hash of subject_pub
  cdk::str subPub = cert.subject_pub;
  cdk::str hash = HASH(SHA,strSubPub, 1);
  cdk::str oid;
  oid = Obj*id_ce_authorityKeyIdentifier;
  return Seq*(oid + Oct*(Seq*(x80*hash + xA1*(xA4*(Seq*(cert.subject))) 
    + x82*bigend(cert.serial))));

cdk::str mkCRLNumberExt(int crlNumber)
  cdk::str oid = Obj*id_ce_cRLNumber; 
  return Seq*(oid + Oct*(asn::integer(crlNumber)));

See RFC 3280 for details.

Certificate and CRL Checking

The following code shows how to check the validity of a certificate pair (i.e., one link in a certificate path).

cdk::str issuerCert =            // the purported issuer certificate

cdk::str subjectCert =           // the subject certificate

// decode the certificates if they are base64-encoded
if (issuerCert[0] != 0x30) issuerCert = issuerCert.tobin64();
if (subjectCert[0] != 0x30) subjectCert = subjectCert.tobin64();

// check the signature in subjectCert using public key in issuerCert
int i = cdk::checkcert(issuerCert, subjectCert);
// checkcert() returns 0 if certificate is valid, non-zero otherwise
printf("Certificate is %s\n", i ? "INVALID!" : "valid");

The following code shows how to test a certificate against a CRL.

cdk::str strCertificate =        // a base64-encoded certificate

cdk::str strCRL =                // a base64-encoded CRL

// decode the certificate or CRL if either is base64-encoded
if (strCertificate[0] != 0x30) strCertificate = strCertificate.tobin64();
if (strCRL[0] != 0x30) strCRL = strCRL.tobin64();

cdk::CRL crl;           // instantiate a CRL object and load the
crl.load(strCRL);       // ASN.1 encoded CRL (test return code for error)

// check to see if the certificate has been revoked
cdk::Cert::Time tDate;  // output buffer for revocation date (if any)
int nReason;            // reason for revocation (if any)
int i = crl.isRevoked(strCertificate, tDate, nReason);
if (i) 
    printf("Certificate has been revoked: reason code = %d\n", nReason);
    printf("Certificate does not appear on this CRL\n");

Issuing an OCSP Status Request

The following function illustrates how to implement a simple OCSP client:

int OCSP_CheckCert(const str &caCert, const str &subCert, const str &svrURL, 
  const str &svrCert)
  /* issue an OCSP status request
        caCert   issuer certificate
        subCert  subject certificate whose validity is to be tested
        svrURL   URL of OCSP responder
        svrCert  responder certificate (for authentication of response)
        0 if certificate is valid
        1 if certificate has been revoked
        2 if certificate status is unknown (responder not authoritative for this CA)
        3 protocol error
        4 signature on response is invalid (reponse cannot be trusted)
  // build the OCSP request
  cdk::str nonce = cdk::getrand2(16);
  cdk::str req = cdk::make_ocsp_req(caCert, subCert, nonce);
  // query the server
  CAmHttpSocket http;
  http.m_lpszContentType = "Content-Type: application/ocsp-request \r\n";
  std::string sResponse = http.GetPage(svrURL.c_str(), true, req.c_str(), req.length());
  cdk::str res = str_(sResponse);

  // check the response (and its signature)
  cdk::asn sinfo, certs, dn;
  cdk::TimeT revtime;
  int i = check_ocsp(req, res, sinfo, revtime, certs, dn);
  if ( (i == 0) || (i == 1) )   // if OK or revoked, check responder's signature
    if ( check_signinfo(svrCert, sinfo) != 0 )
      i = 4;    //signature is invalid!
  return i;

OCSP is specified in RFC 2560. The CAmHttpSocket class used here for the HTTP POST operation is available from the Code Project.

The next topic is Handling Public and Private Keys.

ISC Cryptographic Development Kit - User's Guide
ISC website
Questions? E-mail ISC technical support
Copyright© 2002-2006 Information Security Corp. All rights reserved.