【问题标题】:How to convert pkcs8 to pkcs12 in Java如何在 Java 中将 pkcs8 转换为 pkcs12
【发布时间】:2014-02-17 14:59:47
【问题描述】:

我知道这可以通过 openssl 实现。 但我想知道是否有使用任何库在 Java 中进行 PKCS 转换的可能性(pkcs8 到 12)。

【问题讨论】:

    标签: java pkcs#12 pkcs#8


    【解决方案1】:

    首先您将 PKCS#8 编码的密钥作为文件读取并创建 PrivateKey 对象

    public PrivateKey loadPrivateKey(String keyFile)
        throws Exception {
    
        File f = new File(keyFile);
        FileInputStream fis = new FileInputStream(f);
        DataInputStream dis = new DataInputStream(fis);
        byte[] keyBytes = new byte[(int) f.length()];
        dis.readFully(keyBytes);
        dis.close();
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        return kf.generatePrivate(spec);
    }
    

    然后这个密钥被保存到 PKCS#12 密钥库中

    public void createKeyStore(String keyStorePwd, String keyStoreFile,
        PrivateKey privateKey, X509Certificate certificate)
        throws Exception {
    
        char[] pwd = keyStorePwd.toCharArray();
    
        KeyStore ks = KeyStore.getInstance("PKCS12");
        ks.load(null, pwd);
    
        KeyStore.ProtectionParameter protParam =
            new KeyStore.PasswordProtection(pwd);
        Certificate[] certChain =
            new Certificate[]{ certificate };
        KeyStore.PrivateKeyEntry pkEntry =
            new KeyStore.PrivateKeyEntry(privateKey, certChain);
        ks.setEntry("keypair", pkEntry, protParam);
    
        FileOutputStream fos = new FileOutputStream(keyStoreFile);
        ks.store(fos, pwd);
        fos.close();
    }
    

    【讨论】:

      猜你喜欢
      • 2018-11-15
      • 2019-04-02
      • 1970-01-01
      • 1970-01-01
      • 2021-11-12
      • 1970-01-01
      • 2015-01-21
      • 2017-07-23
      • 2011-06-27
      相关资源
      最近更新 更多