Java读取证书、公钥、私钥

本文介绍了一个Java程序示例,该程序演示了如何从PKCS12格式的密钥库中读取私钥及其相关信息,并展示了如何读取公钥证书文件。通过这个例子,读者可以了解到密钥库的基本操作,包括加载密钥库、获取私钥别名、读取公钥等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


  1. import java.io.ByteArrayOutputStream;
  2. import java.io.FileInputStream;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.security.KeyStore;
  6. import java.security.PrivateKey;
  7. import java.security.PublicKey;
  8. import java.security.cert.Certificate;
  9. import java.security.cert.CertificateException;
  10. import java.util.Enumeration;
  11. import com.sun.org.apache.xml.internal.security.utils.Base64;
  12. import com.help.Conf_Info;
  13. public class VerifiSign2
  14. {
  15. public void main(String[] args)
  16. {
  17. getPrivateKeyInfo();
  18. getPublicKeyInfo();
  19. }
  20. /**
  21. * 获取私钥别名等信息
  22. */
  23. public String getPrivateKeyInfo()
  24. {
  25. String privKeyFileString = Conf_Info.PrivatePath;
  26. String privKeyPswdString = "" + Conf_Info.password;
  27. String keyAlias = null;
  28. try
  29. {
  30. KeyStore keyStore = KeyStore.getInstance( "PKCS12");
  31. FileInputStream fileInputStream = new FileInputStream(privKeyFileString);
  32. char[] nPassword = null;
  33. if ((privKeyPswdString == null) || privKeyPswdString.trim().equals( ""))
  34. {
  35. nPassword = null;
  36. } else
  37. {
  38. nPassword = privKeyPswdString.toCharArray();
  39. }
  40. keyStore.load(fileInputStream, nPassword);
  41. fileInputStream.close();
  42. System.out.println( "keystore type=" + keyStore.getType());
  43. Enumeration<string> enumeration = keyStore.aliases();
  44. if (enumeration.hasMoreElements())
  45. {
  46. keyAlias = (String) enumeration.nextElement();
  47. System.out.println( "alias=[" + keyAlias + "]");
  48. }
  49. System.out.println( "is key entry=" + keyStore.isKeyEntry(keyAlias));
  50. PrivateKey prikey = (PrivateKey) keyStore.getKey(keyAlias, nPassword);
  51. Certificate cert = keyStore.getCertificate(keyAlias);
  52. PublicKey pubkey = cert.getPublicKey();
  53. System.out.println( "cert class = " + cert.getClass().getName());
  54. System.out.println( "cert = " + cert);
  55. System.out.println( "public key = " + pubkey);
  56. System.out.println( "private key = " + prikey);
  57. } catch (Exception e)
  58. {
  59. System.out.println(e);
  60. }
  61. return keyAlias;
  62. }
  63. /**
  64. * 获取公钥信息
  65. */
  66. public void getPublicKeyInfo()
  67. {
  68. String tmp0 = Conf_Info.Public_cer;
  69. String tmp1 = "";
  70. try
  71. {
  72. tmp1 = getPublicKey(Conf_Info.PublicCerPath).replaceAll( "\n", "");
  73. System.out.println( "商户公钥字符串:\n" + tmp1);
  74. System.out.println( "\n商户公钥字符给定串:\n" + tmp0);
  75. if (tmp0.equals(tmp1))
  76. System.out.println( "=========");
  77. else
  78. {
  79. System.out.println( "**************");
  80. }
  81. } catch (CertificateException e)
  82. {
  83. e.printStackTrace();
  84. System.out.println(e);
  85. } catch (IOException e)
  86. {
  87. e.printStackTrace();
  88. System.out.println(e);
  89. }
  90. }
  91. /**
  92. * 读取公钥cer
  93. *
  94. * @param path
  95. * .cer文件的路径 如:c:/abc.cer
  96. * @return base64后的公钥串
  97. * @throws IOException
  98. * @throws CertificateException
  99. */
  100. public static String getPublicKey(String path) throws IOException, CertificateException
  101. {
  102. InputStream inStream = new FileInputStream(path);
  103. ByteArrayOutputStream out = new ByteArrayOutputStream();
  104. int ch;
  105. String res = "";
  106. while ((ch = inStream.read()) != - 1)
  107. {
  108. out.write(ch);
  109. }
  110. byte[] result = out.toByteArray();
  111. // res = Base64.byteArrayToBase64(result);
  112. res = Base64.encode(result);
  113. return res;
  114. }
  115. }
Java中,读取.cer (证书) 或.pfx (个人信息交换文件) 文件并获取其中的公钥私钥,通常需要使用`KeyStore`和`Certificate`类,以及`java.security`包下的工具。以下是基本步骤: 1. **加载keystore**: 使用`KeyStore.getInstance()`方法加载keystore,提供正确的类型(如JKS、PKCS12等)和文件路径。 ```java KeyStore keyStore = KeyStore.getInstance("PKCS12"); InputStream in = new FileInputStream("path_to_your_pfx_file.pfx"); keyStore.load(in, "password".toCharArray()); ``` 2. **获取证书链**: 使用`keyStore.getCertificateChain(certAlias)`获取包含证书的链,`certAlias`是证书别名。 3. **获取信任管理器**: 创建`TrustManagerFactory`,然后从keystore中获取`X509TrustManager`。 ```java TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore); TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); ``` 4. **获取公钥私钥**: 对于.cer文件,证书中通常包含公钥,而.pfx还包含了私钥。如果仅需公钥,可以遍历证书链,每个证书都有公开的`getPublicKey()`方法。如果需要私钥,你需要创建`KeyPairGenerator`,并通过`Certificate`对象的`getPrivateKey()`方法得到。 ```java for (Certificate cert : chain) { PublicKey publicKey = cert.getPublicKey(); // 对于PFX,还需处理PrivateKey } ``` 请注意,`.pfx`文件中可能有多个key entry,每个entry对应一对公钥私钥。操作时需要确定所需的密钥对。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值