Search code examples
javajakarta-eejava-8ssl-certificatekeystore

How to retrieve serial number of a cert from a JKS file programmatically?


Given :
path to JKS,
password for the JKS,
alias of the cert

how can I get the serial number of the cert from the JKS, programmatically ?


Solution

  • You can load a certificate from a Java keystore like that:

          char[] pwdArray = "password".toCharArray();
          KeyStore ks = KeyStore.getInstance("JKS");
          ks.load(new FileInputStream("myKeyStore.jks"), pwdArray);
          Certificate cert = ks.getCertificate("MyAlias");
    

    The base Certificate class has no method to access serial numbers, but I assume that you are using X.509 certificates. The you can use the X509Certificate class like that:

          X509Certificate xcert = (X509Certificate) cert;
          BigInteger serial = xcert.getSerialNumber();
    

    You can see details in the API docs at https://docs.oracle.com/javase/7/docs/api/java/security/cert/X509Certificate.html