Java生成安全证书

时间:2015-04-29 07:05:37

标签: java x509

如何在java中生成此命令的模拟输出?

LocalManagedConnection

我接下来

openssl req -x509 -nodes -days 365 -newkey rsa:4096 -keyout server.key -out cert.pem

但结果我收到了另一个长度的公钥和私钥。

1 个答案:

答案 0 :(得分:1)

以下是一个例子:

Date validityBeginDate = new Date(System.currentTimeMillis());
Date validityEndDate = new Date(System.currentTimeMillis() + 365 * 24 * 60 * 60 * 1000); //1 year from now

KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
keyPairGenerator.initialize(4096, new SecureRandom());

KeyPair keyPair = keyPairGenerator.generateKeyPair();

X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
X500Principal dnName = new X500Principal("CN=John Doe");

certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
certGen.setSubjectDN(dnName);
certGen.setIssuerDN(dnName);
certGen.setNotBefore(validityBeginDate);
certGen.setNotAfter(validityEndDate);
certGen.setPublicKey(keyPair.getPublic());
certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

X509Certificate cert = certGen.generate(keyPair.getPrivate(), "BC");

使用PEMWriter输出您的PEM文件。