Created
September 25, 2019 02:59
-
-
Save hkneptune/5334e4d09132dd776d0338c5eb34a928 to your computer and use it in GitHub Desktop.
Get the Serial Number of a X509 Certificate
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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