How to get exponent and modulus value of RSA public key from pfx file/pem file in java

Ajitha Robert picture Ajitha Robert · Jan 3, 2014 · Viewed 24.2k times · Source

I want to extract information about RSA Public Key from the pfx file using java.

I have a pfx file and converted to x509 Pem file. From pem file, Using the below command in terminal:

openssl x509 -in file.pem -text

I am able to view the public key exponent and modulus value


Subject Public Key Info:

Public Key Algorithm: rsaEncryption
    Public-Key: (2048 bit)
    Modulus:
        00:da:7c:e0:3e:c4:62:8d:ce:29:04:2f:93:78:7c:
        :
         6a:e7:c9:7c:8b:6f:09:5c:75:5f:8c:5e:9c:6a:b9:
        7:32:90: a4:4b
    Exponent: 65537 (0x10001)

How to extract the above information in java?

Input: pfxfile and password

Output:public key exponent and modulus value.

I m using the below code to extract the public key exponent and modulus, but i am not getting the value that is extracted using openssl. I doubt whether java.security.cert.Certificate uses some other DER format??

What is the java equivalent of openssl?

Code:

KeyStore ks = KeyStore.getInstance("pkcs12");
ks.load(new FileInputStream(file), password.toCharArray());
Enumeration enumeration = ks.aliases();
while (enumeration.hasMoreElements()) {
    String alias = (String) enumeration.nextElement();
    java.security.cert.Certificate certificate = ks.getCertificate(alias);
    PublicKey publickey = certificate.getPublicKey();
}

Answer

erickson picture erickson · Jan 3, 2014

You need to downcast to the transparent java.security.interfaces.RSAPublicKey type. Then you can access the modulus and public exponents.

KeyStore ks = KeyStore.getInstance("pkcs12");
ks.load(new FileInputStream(file), password.toCharArray());
Enumeration<String> enumeration = ks.aliases();
while (enumeration.hasMoreElements()) {
  String alias = enumeration.nextElement();
  Certificate certificate = ks.getCertificate(alias);
  RSAPublicKey pub = (RSAPublicKey) certificate.getPublicKey();
  System.out.println(pub.getModulus().toString(16));
  System.out.println(pub.getPublicExponent().toString(16));
}