【问题标题】:how to extract private key from .p12 file using java sun security如何使用 java sun security 从 .p12 文件中提取私钥
【发布时间】:2016-10-28 07:06:20
【问题描述】:

这是我的程序。我收到错误“打开密钥文件时出错”。请帮助我哪里出错了。

import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.PrivateKey;
import java.util.Base64;

public class ExtractionClass {
    public static void main(String args[]) {
       String  p12Password = "PassWord";
       try{
       FileInputStream file = new FileInputStream("C:/Users/Aarti_Jangid/Desktop/p12/certChain.p12");
       System.out.println("FILE "+ file);
       KeyStore keystore = KeyStore.getInstance("PKCS12", "SunJSSE");
       keystore.load(file, p12Password.toCharArray());
       String alias = keystore.aliases().nextElement(); 
       PrivateKey key = (PrivateKey)keystore.getKey(alias, p12Password.toCharArray());
       System.out.println(Base64.getEncoder().encodeToString(key.getEncoded()));
       } catch(KeyStoreException kse) {
           kse.printStackTrace();
           System.err.println("Error getting the key");  
       } catch (Exception e) {
              System.err.println("Error opening the key file");
              e.printStackTrace();
     }
   }
}

【问题讨论】:

  • 请将堆栈跟踪也复制粘贴到这里
  • 我认为您的 .p12 文件有问题,如果您使用有效证书,您的代码可以工作,here 您可以找到有效证书。
  • 如果您以编程方式创建 .p12 文件,请查看 here

标签: java security private-key


【解决方案1】:

我假设你的堆栈跟踪是:

Error opening registry key 'C:/Users/Aarti_Jangid/Desktop/p12/certChain.p12'
Error: could not find Java.dll
Error: could not find Java 2 Runtime Environment

如果是这样,试试这个:Java Error opening registry key

【讨论】:

  • FILE java.io.FileInputStream@659e0bfd 在 java.util.LinkedHashMap$LinkedHashIterator.nextNode(Unknown Source) at java.util.LinkedHashMap$LinkedKeyIterator.next 打开密钥文件 java.util.NoSuchElementException 时出错(Unknown Source) at java.util.Collections$3.nextElement(Unknown Source) at ExtractionCode.ExtractionClass.main(ExtractionClass.java:17) Stack Trace 就是这样。我提供了正确的密码,如果我删除 String alias = keystore.aliases().nextElement();然后它给出 keyStoreException - 未初始化的密钥库
  • 我的私钥为空。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-07-25
  • 2011-04-02
  • 1970-01-01
  • 2017-12-15
  • 2020-06-30
  • 2020-05-01
  • 2019-06-07
相关资源
最近更新 更多