Retrieve Subject alternative names of X.509 certificate in java
Asked Answered
M

3

8

I have tried using the solution provided in this link.

I am getting following error when i tried reading subject alternative names of X.509 Certificate

java.lang.NoSuchMethodError: org.bouncycastle.asn1.ASN1InputStream.readObject()Lorg/bouncycastle/asn1/DERObject;

At below line of code

ASN1InputStream decoder = new ASN1InputStream((byte[]) item.toArray());

DEREncodable encoded = decoder.readObject();

.der file is used to create certificate as follows.

X509Certificate cert=null;
fis = new FileInputStream(file.getAbsoluteFile());     //.der file
bis = new BufferedInputStream(fis);

CertificateFactory cf = CertificateFactory.getInstance("X.509");
while (bis.available() > 0) {
                    try{
                    cert = cf.generateCertificate(bis);
                    }
                     catch (CertificateException e) {
                      e.printStackTrace();
                  }
 List list=getSubjectAlternativeNames((X509Certificate) cert);

Below is the solution i got from the link mentioned above.

   public static List<String> getSubjectAlternativeNames(X509Certificate certificate) {
    List<String> identities = new ArrayList<String>();
    try {
        Collection<List<?>> altNames = certificate.getSubjectAlternativeNames();
        // Check that the certificate includes the SubjectAltName extension
        if (altNames == null)
            return Collections.emptyList();
        // Use the type OtherName to search for the certified server name
        for (List item : altNames) {
            Integer type = (Integer) item.get(0);
            if (type == 0)
                // Type OtherName found so return the associated value
                try {
                    // Value is encoded using ASN.1 so decode it to get the server's identity
                    ASN1InputStream decoder = new ASN1InputStream((byte[]) item.toArray()[1]);
                    DEREncodable encoded = decoder.readObject();
                    encoded = ((DERSequence) encoded).getObjectAt(1);
                    encoded = ((DERTaggedObject) encoded).getObject();
                    encoded = ((DERTaggedObject) encoded).getObject();
                    String identity = ((DERUTF8String) encoded).getString();
                    // Add the decoded server name to the list of identities
                    identities.add(identity);
                }
            catch (UnsupportedEncodingException e) {
                e.printStackTrace();
               // log.error("Error decoding subjectAltName" + e.getLocalizedMessage(),e);
            }
            catch (Exception e) {
               // log.error("Error decoding subjectAltName" + e.getLocalizedMessage(),e);
                e.printStackTrace();
            }
            // Other types are not good for XMPP so ignore them
            //log.warn("SubjectAltName of invalid type found: " + certificate);
        }
    }
    catch (CertificateParsingException e) {
        e.printStackTrace();
       // log.error("Error parsing SubjectAltName in certificate: " + certificate + "\r\nerror:" + e.getLocalizedMessage(),e);
    }
    return identities;
}

Is it that i have not used proper .jar file?

.jar i have used is --> bcprov-jdk16-1.45.jar

Suggest me where i have gone wrong.

Madder answered 23/6, 2015 at 4:28 Comment(0)
D
6

I tried with your code for me it is working, I tested with a certificate exported from internet explorer

Internet Explorer -> Tools -> Internet Options -> Content -> Certificates -> Untrusted Publishers -> www.google.com

I exported this as ".cer", I made few changes to your code

public static List<String> getSubjectAlternativeNames(X509Certificate certificate) {
        List<String> identities = new ArrayList<String>();
        try {
            Collection<List<?>> altNames = certificate.getSubjectAlternativeNames();
            if (altNames == null)
                return Collections.emptyList();
            for (List item : altNames) {
                Integer type = (Integer) item.get(0);
                if (type == 0 || type == 2){
                    try {
                        ASN1InputStream decoder=null;
                        if(item.toArray()[1] instanceof byte[])
                            decoder = new ASN1InputStream((byte[]) item.toArray()[1]);
                        else if(item.toArray()[1] instanceof String)
                            identities.add( (String) item.toArray()[1] );
                        if(decoder==null) continue;
                        DEREncodable encoded = decoder.readObject();
                        encoded = ((DERSequence) encoded).getObjectAt(1);
                        encoded = ((DERTaggedObject) encoded).getObject();
                        encoded = ((DERTaggedObject) encoded).getObject();
                        String identity = ((DERUTF8String) encoded).getString();
                        identities.add(identity);
                    }
                    catch (UnsupportedEncodingException e) {
                        log.error("Error decoding subjectAltName" + e.getLocalizedMessage(),e);
                    }
                    catch (Exception e) {
                        log.error("Error decoding subjectAltName" + e.getLocalizedMessage(),e);
                    }
                }else{
                    log.warn("SubjectAltName of invalid type found: " + certificate);
                }
            }
        }
        catch (CertificateParsingException e) {
            log.error("Error parsing SubjectAltName in certificate: " + certificate + "\r\nerror:" + e.getLocalizedMessage(),e);
        }
        return identities;
    }

I saved the file to c:\aa1.cer

X509Certificate cert=null;
        FileInputStream fis = new FileInputStream("c:\\aa1.cer");
        BufferedInputStream bis = new BufferedInputStream(fis);

        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        if (bis.available() > 0)
            try{
               cert = (X509Certificate)cf.generateCertificate(bis);
            }
            catch (CertificateException e) {
                e.printStackTrace();
            }
        System.out.println(CertificateInfo.getSubjectAlternativeNames(cert));

I got the output as [www.google.com, google.com]

Please check your certificate, I think the problem is your certificate

Daina answered 23/6, 2015 at 7:36 Comment(2)
Thanks for the solution.Yes, It is working for .cer file which i took from IE. I need it for .der file as well.Madder
Problem is with my certificate only.Madder
K
1

Many examples use hard-coded integers. For readability, I much prefer to use:

  • GeneralName.dNSName = 2
  • GeneralName.iPAddress = 7
  • ... etc

The code:

public static String[] parseHostNames(X509Certificate cert) {
    List<String> hostNameList = new ArrayList<>();
    try {
        Collection<List<?>> altNames = cert.getSubjectAlternativeNames();
        if (altNames != null) {
            for(List<?> altName : altNames) {
                if(altName.size()< 2) continue;
                switch((Integer)altName.get(0)) {
                    case GeneralName.dNSName:
                    case GeneralName.iPAddress:
                        Object data = altName.get(1);
                        if (data instanceof String) {
                            hostNameList.add(((String)data));
                        }
                        break;
                    default:
                }
            }
        }
        System.out.println("Parsed hostNames: " + String.join(", ", hostNameList));
    } catch(CertificateParsingException | IOException e) {
        System.err.println("Can't parse hostNames from this cert.");
        e.printStackTrace();
    }
    return hostNameList.toArray(new String[hostNameList.size()]);
}

Note: The accepted answer checks for byte[], but won't compile on my system. I found some other examples using byte[] by calling new ASN1InputStream((byte[])data).readObject();, but I have no certificate to test it with, so I've removed it from my example.

Khajeh answered 16/10, 2019 at 21:26 Comment(0)
R
0

For me, this method worked fine. And the library version that I found to be working fine is this one:

bcprov-jdk15-1.46.jar

private String getOtherNameValue(X509Certificate certificate) {
        final String method = "[getOtherNameValue] - ";
        System.out.println(method + "START");
        Collection<List<?>> altNames = null;
        try {
            altNames = certificate.getSubjectAlternativeNames();
        } catch (CertificateParsingException e) {
            e.printStackTrace();
        }
        if (altNames == null)
            return "";
        for (List item : altNames) {
            Integer type = (Integer) item.get(0);
            if (type == 0) {
                try {
                    ASN1InputStream decoder = null;
                    if (item.toArray()[1] instanceof byte[])
                        decoder = new ASN1InputStream((byte[]) item.toArray()[1]);
                    if (decoder == null)
                        continue;
                    DEREncodable encoded = decoder.readObject();
                    encoded = ((DERSequence) encoded).getObjectAt(1);
                    encoded = ((DERTaggedObject) encoded).getObject();
                    encoded = ((DERTaggedObject) encoded).getObject();
                    String principalName = ((DERUTF8String) encoded).getString();
                    System.out.println(method + "END with principalName: " + principalName);
                    return principalName;
                } catch (Exception e) {
                    System.out.println(method + "Exception decoding subjectAltName" + e.getLocalizedMessage());
                    e.printStackTrace();
                }
            }
        }
        System.out.println(method + "END");
        return "";
    }
Registry answered 17/8, 2023 at 6:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.