Generate random certificates

2020-06-16 05:11发布

I am looking for a utility class that can generate random certificate strings for testing purposes. Any idea if there is one already implemented?

标签: java
2条回答
狗以群分
2楼-- · 2020-06-16 06:09

The built-in Java X500 libraries are geared more towards using certificates than generating and parsing certificates. You might find a way to do what you want, but it would almost certainly be messy and in a protected API (sun.security.*).

I suggest you include the Bouncy Castle library (Apache License). It has a class called X509V3CertificateGenerator that you can use to set the fields of a certificate (issuer, subject, expiry date, etc).

You should then be able to get the PEM string from it using the PEMWriter class.

查看更多
你好瞎i
3楼-- · 2020-06-16 06:12

To add to solution given by martijno,

Instead of writing your own content signer, JCAContentSigner can be used to avoid mappings to AlgorithmIdentifier (i.e. OID).

JcaContentSignerBuilder takes algorithm names as defined here.

X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuer, serialNumber, startDate, expiryDate, subject, SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()));
JcaContentSignerBuilder builder = new JcaContentSignerBuilder("SHA256withRSA");
ContentSigner signer = builder.build(keyPair.getPrivate());

byte[] certBytes = certBuilder.build(signer).getEncoded();
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
X509Certificate certificate = (X509Certificate)certificateFactory.generateCertificate(new ByteArrayInputStream(certBytes));
查看更多
登录 后发表回答