Skip to content

Java Bouncy Castle OCSP Url

I am using bouncy castle 1.48 to verify certificate validation with OCSP. It works good. But I’m using Ocsp Url as static variable and I want to read it from certificate. Url is written in certificate as Authority Info Access

[1]Authority Info Access
 Access Method=On-line Certificate Status Protocol (1.3.6.1.5.5.7.48.1)
 Alternative Name:
      URL=http://ocsp.mydomain

I got org.bouncycastle.asn1.x509.AuthorityInformationAccess object from certificate

byte[] octetBytes = certificate.getExtensionValue(X509Extension.authorityInfoAccess.getId());
ASN1InputStream octetStream = new ASN1InputStream(octetBytes);
byte[] encoded = X509ExtensionUtil.fromExtensionValue(octetBytes).getEncoded();
ASN1Sequence seq = ASN1Sequence.getInstance(ASN1Primitive.fromByteArray(encoded));
AuthorityInformationAccess access = AuthorityInformationAccess.getInstance(seq);

which writes AuthorityInformationAccess: Oid(1.3.6.1.5.5.7.48.1) but cant get Url from there

Answer

I found the way.

private String getOcspUrl(X509Certificate certificate) throws Exception {
    byte[] octetBytes = certificate
            .getExtensionValue(X509Extension.authorityInfoAccess.getId());

    DLSequence dlSequence = null;
    ASN1Encodable asn1Encodable = null;

    try {
        ASN1Primitive fromExtensionValue = X509ExtensionUtil
                .fromExtensionValue(octetBytes);
        if (!(fromExtensionValue instanceof DLSequence))
            return null;
        dlSequence = (DLSequence) fromExtensionValue;
        for (int i = 0; i < dlSequence.size(); i++) {
            asn1Encodable = dlSequence.getObjectAt(i);
            if (asn1Encodable instanceof DLSequence)
                break;
        }
        if (!(asn1Encodable instanceof DLSequence))
            return null;
        dlSequence = (DLSequence) asn1Encodable;
        for (int i = 0; i < dlSequence.size(); i++) {
            asn1Encodable = dlSequence.getObjectAt(i);
            if (asn1Encodable instanceof DERTaggedObject)
                break;
        }
        if (!(asn1Encodable instanceof DERTaggedObject))
            return null;
        DERTaggedObject derTaggedObject = (DERTaggedObject) asn1Encodable;
        byte[] encoded = derTaggedObject.getEncoded();
        if (derTaggedObject.getTagNo() == 6) {
            int len = encoded[1];
            return new String(encoded, 2, len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}