Parse X509Certificate to JSON

Parsing a X509Certificate file into JSON object in string using groovy is demonstrated here.

import groovy.json.JsonOutput
import groovy.json.JsonSlurper

import java.security.cert.CertificateFactory
import java.security.cert.X509Certificate

class CertificateParser {

  public static def parseFileToJson(def path) {
    return toJason(parseX509Certificate(new File(path).newInputStream()))
  }

  private static def toJason(X509Certificate certificate){
    def builder = new groovy.json.JsonBuilder()
    def timeZone = TimeZone.getTimeZone("America/New_York")
    builder{
      expiryDate certificate.getNotAfter().format("yyyy-MM-dd hh:mm:ss", timeZone)
      subjectDN certificate.getSubjectDN()
      subjectAlternativeNames CertificateParserHelper.getSubjectAltName(certificate)
      eku CertificateParserHelper.getExtendedKeyUsageAsText(certificate)
      issuerDN certificate.getIssuerDN()
      issuerUniqueID certificate.getIssuerUniqueID()
      issuerAlternativeNames certificate.getIssuerAlternativeNames()
      issuerX500Principal certificate.getIssuerX500Principal()
      subjectUniqueID certificate.getSubjectUniqueID()
      subjectX500Principal certificate.getSubjectX500Principal()
      serialNumber certificate.getSerialNumber()
      sigAlgName certificate.getSigAlgName()
      sigAlgOID certificate.getSigAlgOID()
      signature certificate.getSignature()
      type certificate.getType()
      version certificate.getVersion()
    }
    return JsonOutput.prettyPrint(builder.toString())
  }

  private static def parseX509Certificate(def inputStream){
    def CertificateFactory cf = CertificateFactory.getInstance("X.509");
    return inputStream.withStream { s->
      (X509Certificate)cf.generateCertificate(s)
    }
  }
}

The helper class can be found below as

import java.security.cert.X509Certificate
class CertificateParserHelper {
  private static final EXTENDED_KEY_USAGE_OID_STRINGS = [
    "2.5.29.37.0",
    "1.3.6.1.5.5.7.3.0",
    "1.3.6.1.5.5.7.3.1",
    "1.3.6.1.5.5.7.3.2",
    "1.3.6.1.5.5.7.3.3",
    "1.3.6.1.5.5.7.3.4",
    "1.3.6.1.5.5.7.3.5",
    "1.3.6.1.5.5.7.3.6",
    "1.3.6.1.5.5.7.3.7",
    "1.3.6.1.5.5.7.3.8",
    "1.3.6.1.4.1.311.20.2.2",
    "1.3.6.1.5.5.7.3.9"
  ];

  private static final EXTENDED_KEY_USAGE_TEXTS = [
    "All Usages",
    "All Usages",
    "Server Authentication",
    "Client Authentication",
    "Code Signing",
    "Email Protection",
    "IPSec end system",
    "IPSec tunnel",
    "IPSec user",
    "Timestamping",
    "Smartcard Logon",
    "OCSP signer"
  ];


  public static List<String> getExtendedKeyUsageAsText(X509Certificate certificate) {
    def extendedKeyUsageOidToTextMap = [EXTENDED_KEY_USAGE_OID_STRINGS, EXTENDED_KEY_USAGE_TEXTS].transpose().collectEntries{it}
    try {
      def extendedkeyusage = certificate.getExtendedKeyUsage();
      if (extendedkeyusage == null){
        return [];
      }
      def returnval = []
      extendedkeyusage.each{it->
        returnval.push(extendedKeyUsageOidToTextMap.get(it));
      }
      return returnval;
    } catch (java.security.cert.CertificateParsingException e) {
      //log.error("certificate parsing exception" + e.getLocalizedMessage(), e);
      throw e;
    }
  }

  public static getSubjectAltName(X509Certificate certificate) {
    def result=[]
    def sans = certificate.getSubjectAlternativeNames()
    try {
      if ( sans!= null) {
        sans.each {iter->
          String name = (String)iter.get(1);
          if (name != null){
            result.push(name);
          }
        }
      }
    } catch (java.security.cert.CertificateParsingException e) {
      result = e.getMessage();
    }

    return result;
  }
}

Advertisements
This entry was posted in Groovy and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s