用Java获取x509策略

时间:2018-04-17 14:54:48

标签: java ssl-certificate bouncycastle x509certificate x509

我无法从x509证书中提取策略。出现的错误是:线程" main"中的异常。

我正在使用BouncyCastle,但我对此并不了解。

public class X509Reader {
    private static ASN1InputStream asn1InputStream;


    public static void main(String[] args){
        try {
            FileInputStream fis = new FileInputStream("certificate.pem");
            BufferedInputStream bis = new BufferedInputStream(fis);

            CertificateFactory cf = CertificateFactory.getInstance("X.509");

            while(bis.available() > 0){

                Certificate cert = cf.generateCertificate(bis);
                X509Certificate x = (X509Certificate) cert;


                byte[] policyBytes = x.getExtensionValue("2.5.29.33");
                asn1InputStream = new ASN1InputStream(policyBytes);
                Object policy = asn1InputStream.readObject();           


                System.out.println("Policy:" + policy);
                System.out.println("\n");
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (CertificateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }
}

我应该怎么做才能修复它?

编辑:

stacktrace:

  

线程中的异常" main" java.lang.NullPointerException at   java.io.ByteArrayInputStream。(ByteArrayInputStream.java:106)at   org.bouncycastle.asn1.ASN1InputStream。(未知来源)at   parser.X509Reader.main(X509Reader.java:48)

1 个答案:

答案 0 :(得分:0)

以下是如何使用最近的 BouncyCastle 从证书中提取策略:

import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.x509.CertificatePolicies;
import org.bouncycastle.asn1.x509.Extension;
import org.bouncycastle.asn1.x509.PolicyInformation;
import org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils;

...

X509Certificate certificate = (X509Certificate)cf.generateCertificate(bis);
byte[] extensionValue = certificate.getExtensionValue(
    Extension.certificatePolicies.getId()
);
CertificatePolicies policies = CertificatePolicies.getInstance(
    JcaX509ExtensionUtils.parseExtensionValue(extensionValue)
);
Set<ASN1ObjectIdentifier> policyIds = Arrays.stream(policies.getPolicyInformation())
        .map(PolicyInformation::getPolicyIdentifier)
        .collect(Collectors.toSet());