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
Many examples use hard-coded integers. For readability, I much prefer to use:
GeneralName.dNSName
= 2
GeneralName.iPAddress
= 7
The code:
public static String[] parseHostNames(X509Certificate cert) {
List hostNameList = new ArrayList<>();
try {
Collection> 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.