Skip to content

Instantly share code, notes, and snippets.

@hkneptune
Created September 25, 2019 02:59
Show Gist options
  • Save hkneptune/5334e4d09132dd776d0338c5eb34a928 to your computer and use it in GitHub Desktop.
Save hkneptune/5334e4d09132dd776d0338c5eb34a928 to your computer and use it in GitHub Desktop.
Get the Serial Number of a X509 Certificate
package com.neptuneli.utils;
import java.math.BigInteger;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
public class X509CertificateUtils {
public String getCertSerialNo(final String certPath) {
FileInputStream fileInputStream = null;
String serialNo = null;
try {
fileInputStream = new FileInputStream(certPath);
final BouncyCastleProvider provider = new BouncyCastleProvider();
final CertificateFactory certificateFactory = CertificateFactory.getInstance("X509", provider);
final X509Certificate certificate = (X509Certificate) certificateFactory.generateCertificate(fileInputStream);
final BigInteger serialNumber = certificate.getSerialNumber();
serialNo = serialNumber.toString();
} catch (final FileNotFoundException e1) {
e1.printStackTrace();
System.err.println("Cannot find the X509 certificate");
} catch (final Exception e2) {
e2.printStackTrace();
System.err.println("Cannot parse the serial number");
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (final IOException e3) {
e3.printStackTrace();
System.err.println("Cannot close the certificate input stream");
}
}
}
return serialNo;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment