7

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

Joly
  • 3,218
  • 14
  • 44
  • 70

2 Answers2

7

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));
Camath
  • 71
  • 1
  • 1
  • Am i right if this isn't a self signed cert i just replace the private key with the private key of the CA? – maxbit89 Jun 30 '17 at 13:47
4

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.

Mark Peters
  • 80,126
  • 17
  • 159
  • 190