How to create X509Certificate with keys pairs without sun.security

Viewed 2076

I want to generate x509 certificate and keys pairs for my unit test.

private Pair<String, String> generateTokenAndCertificate() {
    try {

        //Configure generator
        CertAndKeyGen certGen = new CertAndKeyGen("RSA", "SHA256WithRSA");
        certGen.generate(2048);
        long validSecs = (long) 365 * 24 * 60 * 60; // valid for one year


        //Token
        CharSequence content = "test";
        Signer signer = new RsaSigner((RSAPrivateKey) certGen.getPrivateKey());
        String token = JwtHelper.encode(content, signer).getEncoded();

        //Certificate
        X500Name data = new X500Name("CN=Test Application,O=Company,L=City,C=DE");
        X509Certificate cert = certGen.getSelfCertificate(data, validSecs);
        Base64 encoder = new Base64();
        String certificate = X509Factory.BEGIN_CERT + "\n";
        certificate += encoder.encode(cert.getEncoded());
        certificate += X509Factory.END_CERT + "\n";

        return new Pair<>(token, certificate);
    } catch (Exception e) {
        return null;
    }
}

The problem is that I have used

import sun.security.provider.X509Factory;
import sun.security.tools.keytool.CertAndKeyGen;
import sun.security.x509.X500Name;

And got errors like these:

error: package sun.security.tools.keytool does not exist

and:

error: cannot find symbol
        CertAndKeyGen certGen = new CertAndKeyGen("RSA", "SHA256WithRSA");
        ^
symbol:   class CertAndKeyGen
location: class CertificationProviderSpecification

I know that javac doesn't load full rt.jar regarding ct.sym and I could solve such errors by -XDignore.symbol.file or Bouncy Castle.

But is it possible to generate these by java.security or org.springframework.security?

1 Answers
Related