从PKCS12文件导出PublicKey和PrivateKey [英] Export PublicKey and PrivateKey from PKCS12 file

查看:439
本文介绍了从PKCS12文件导出PublicKey和PrivateKey的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个.p12文件,我想导出公共和私有密钥.我使用了这种方法:

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();

第二种方法是使用openssl命令并将其转换为.cer文件:

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

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

第三种方法是将该cert.cer文件加载到密钥库并获取密钥

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

推荐答案

在第一个示例中,您正在读取PKCS12类型的密钥库文件.在密钥库中,插入了一个或多个私钥.对于每个私钥条目,存在一个证书或一个包含许多证书的证书链.因此,在这里通过提供正确的别名和密钥库密码,您将同时获得私钥和证书.从证书中,您将获得它的公钥

在第二个示例中,您仅从密钥库文件中获取证书.因此,在这里您没有得到公共密钥,而是得到了包含公共密钥的证书.为了从证书获取公钥,请在命令后运行以下命令:

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.

这篇关于从PKCS12文件导出PublicKey和PrivateKey的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆