Export PublicKey and PrivateKey from PKCS12 file

我们两清 提交于 2020-03-22 07:21:12

问题


I have a .p12 file and I want to export a public and private keys. I used this method:

FileInputStream fm = new FileInputStream("C:\\cert.p12");
    KeyStore ks = KeyStore.getInstance("PKCS12");
    try {
        ks.load(fm, "pass".toCharArray());
    } catch (Exception e) {
        e.printStackTrace();
    }
    Key key = ks.getKey("cert", "pass".toCharArray());
    Certificate cert = ks.getCertificate("cert");
    PublicKey publicKey = cert.getPublicKey();
    System.out.println("Public key");
    System.out.println(Base64.getEncoder().encodeToString(
            publicKey.getEncoded()));
    fm.close();

The second method was to use openssl command and convert it to .cer file:

openssl pkcs12 -in cert.p12 -out cert.cer -nodes

The third method was to load this cert.cer file to keystore and get key

    FileInputStream fm1;
    fm1 = new FileInputStream("C:\\cert.cer");
    CertificateFactory f = CertificateFactory.getInstance("X.509");
    X509Certificate certificate = (X509Certificate)f.generateCertificate(fm1);
    PublicKey pk = certificate.getPublicKey();
    System.out.println("Public key");
    System.out.println(Base64.getEncoder().encodeToString(pk.getEncoded()));

So my question is why the first public key is the same like in third method but different than in second method. How should i export this key? thanks for reply


回答1:


In the first example, you are reading a PKCS12 type keystore file. In the keystore, one or more private key(s) is inserted. for every private key entry, one certificate or one certificate chain containing many certificates exist. So, here by giving correct alias and keystore password, you are getting Both private key and certificate. And from the certificate, you are getting it's public key

In the second example, you are getting only certificate from the keystore file. So, here you are not getting public key but the certificate that contains the public key. In order to get the public key from certificate, run following command after your command:

openssl x509 -inform pem -in certificate.der -pubkey -noout > publickey.pem

Now, in the third example, you already have a certificate file to read. You are reading the certificate and get the public key from the certificate.

Hope that, it clears your confusion.



来源:https://stackoverflow.com/questions/31803335/export-publickey-and-privatekey-from-pkcs12-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!