How to create a X509 certificate using Java?(如何使用 Java 创建 X509 证书?)
问题描述
我想使用 Java 语言创建一个 X509 证书,然后从中提取公钥.
I want to create a X509 certificate using Java language and then extract public key from it.
我搜索了互联网并找到了许多代码示例,但它们都有错误(未知变量或未知类型)或有许多警告说:方法......来自类型......已被弃用"等等
I have searched the internet and found many code examples, but all of them have errors (unknown variable or unknown type) or have many warnings that say something like : "the method ... from type ... is deprecated " etc.
例如,为什么下面的代码不起作用:
For example, why the following code doesn't work:
PublicKey pk;
CertificateFactory cf = CertificateFactory.getInstance("X.509");
String PKstr = pk.toString();
InputStream PKstream = new ByteArrayInputStream(PKstr.getBytes());
X509Certificate pkcert = (X509Certificate)cf.generateCertificate(PKstream);
谁能告诉我如何使用纯 Java 或 Bouncy Castle 创建证书,然后从中获取公钥?
Can anyone show me how to create a certificate using pure Java or Bouncy Castle and then get a public key from that?
谢谢大家.
推荐答案
您也可以仅使用 JDK 类生成证书.缺点是您必须使用 sun.security.x509 包中的两个类.代码是:
You can also generate a certificate using only JDK classes. The disadvantage is that you have to use two classes from the sun.security.x509 package. The code would be:
KeyStore keyStore = ... // your keystore
// generate the certificate
// first parameter = Algorithm
// second parameter = signrature algorithm
// third parameter = the provider to use to generate the keys (may be null or
// use the constructor without provider)
CertAndKeyGen certGen = new CertAndKeyGen("RSA", "SHA256WithRSA", null);
// generate it with 2048 bits
certGen.generate(2048);
// prepare the validity of the certificate
long validSecs = (long) 365 * 24 * 60 * 60; // valid for one year
// add the certificate information, currently only valid for one year.
X509Certificate cert = certGen.getSelfCertificate(
// enter your details according to your application
new X500Name("CN=My Application,O=My Organisation,L=My City,C=DE"), validSecs);
// set the certificate and the key in the keystore
keyStore.setKeyEntry(certAlias, certGen.getPrivateKey(), null,
new X509Certificate[] { cert });
从密钥库中检索私钥以加密或解密数据.基于代码来自 http://www.pixeltech.net/article/1408524957-Generate-certificate-in-Java----3
Retrieve the private key from the key store to encrypt or decrypt data. Based on the code is from http://www.pixelstech.net/article/1408524957-Generate-cetrificate-in-Java----3
这篇关于如何使用 Java 创建 X509 证书?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 Java 创建 X509 证书?
基础教程推荐
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01