X509CertBuilder { public static void addKeyPair( KeyStore keystore, String alias, char[] privateKeyPassword, String commonName, String unit, String organization, String location, String state, String country, String emailAdress) throws GeneralSecurityException, OperatorCreationException { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALG); keyPairGenerator.initialize(KEY_SIZE); KeyPair keyPair = keyPairGenerator.generateKeyPair(); String x500Name = Stream .of( Pair.of("CN", commonName), Pair.of("OU", unit), Pair.of("O", organization), Pair.of("L", location), Pair.of("ST", state), Pair.of("C", country), Pair.of("EmailAddress", emailAdress)) .filter(p -> p.getRight() != null) .map(p -> p.getLeft() + "=" + p.getRight()) .collect(Collectors.joining(",")); BigInteger serial = BigInteger.valueOf(new Random().nextLong()); X500Name subject = new X500Name(x500Name); PublicKey pubKey = keyPair.getPublic(); LocalDateTime yesterday = LocalDateTime.now().minusDays(1); X509v3CertificateBuilder generator = new JcaX509v3CertificateBuilder( new X500Name(x500Name), serial, toDate(yesterday), toDate(yesterday.plusYears(VALIDITY_YRS)), subject, pubKey); ContentSigner sigGen = new JcaContentSignerBuilder(SIG_ALG).build(keyPair.getPrivate()); X509CertificateHolder certHolder = generator.build(sigGen); X509Certificate cert = new JcaX509CertificateConverter().getCertificate(certHolder); keystore.setKeyEntry( alias, keyPair.getPrivate(), privateKeyPassword, new Certificate[] { cert }); } private  X509CertBuilder(); static KeyStore createTemporaryCert(String commonName, String alias, String password); static void addKeyPair(
		KeyStore keystore,
		String alias,
		char[] privateKeyPassword,
		String commonName,
		String unit,
		String organization,
		String location,
		String state,
		String country,
		String emailAdress);  }
@Test public void testAddKeyPair() throws Exception { KeyStore keyStore = KeyStore.getInstance("jks"); keyStore.load(null, "ksPass".toCharArray()); X509CertBuilder.addKeyPair(keyStore, "key1", "keyPass1".toCharArray(), "k1", null, null, null, null, null, null); X509CertBuilder.addKeyPair(keyStore, "key2", "keyPass2".toCharArray(), "k2", null, null, null, null, null, null); assertEquals(keyStore.size(), 2); assertTrue(keyStore.isKeyEntry("key1")); Key key = keyStore.getKey("key1", "keyPass1".toCharArray()); assertEquals(key.getFormat(), "PKCS#8"); Certificate cert = keyStore.getCertificate("key1"); assertEquals(cert.getType(), "X.509"); X509Certificate x509Cert = (X509Certificate) cert; assertEquals(x509Cert.getSubjectDN().getName(), "CN=k1"); assertEquals(cert.getPublicKey().getAlgorithm(), "RSA"); assertEquals(x509Cert.getSigAlgName(), "SHA256withRSA"); assertEquals(((RSAKey) cert.getPublicKey()).getModulus().bitLength(), 4096); cert.verify(cert.getPublicKey()); }