@SuppressWarnings("restriction") public static void generate(SelfSignedCertInfo info, String keystore, char[] keystorePassword) throws Exception { U.must(U.notEmpty(info.alias()), "The alias must be specified!"); U.must(info.password() != null, "The password must be specified!"); CertAndKeyGen certAndKeyGen = new CertAndKeyGen("RSA", "SHA1WithRSA", null); certAndKeyGen.generate(info.keysize()); long validityInSeconds = info.validity() * 24 * 3600; X509Certificate[] cert = {certAndKeyGen.getSelfCertificate(x500Name(info), new Date(), validityInSeconds)}; KeyStore store = KeyStore.getInstance("JKS"); if (new File(keystore).exists()) { store.load(new FileInputStream(keystore), keystorePassword); } else { store.load(null, null); } store.setKeyEntry(info.alias(), certAndKeyGen.getPrivateKey(), info.password(), cert); store.store(new FileOutputStream(keystore), keystorePassword); }
/** * Creates a self certificate, stores it into a keystore and adapts the server options to use that certificate * * @param options * @param hostName * @param password * @throws GeneralSecurityException * @throws IOException */ @SuppressWarnings("restriction") public static void createSelfCertificate(HttpServerOptions options, String hostName, String password) throws GeneralSecurityException, IOException { LOGGER.info("creating self certificate"); KeyStore store = KeyStore.getInstance("JKS"); store.load(null, null); sun.security.tools.keytool.CertAndKeyGen keypair = new sun.security.tools.keytool.CertAndKeyGen("RSA", ALGORYTM, null); sun.security.x509.X500Name x500Name = new sun.security.x509.X500Name(hostName, "IT", "firm", "city", "country", "state"); keypair.generate(1024); PrivateKey privKey = keypair.getPrivateKey(); java.security.cert.X509Certificate[] chain = new java.security.cert.X509Certificate[1]; chain[0] = keypair.getSelfCertificate(x500Name, new Date(), (long) 365 * 24 * 60 * 60); store.setKeyEntry("selfsigned", privKey, password.toCharArray(), chain); FileOutputStream fo = new FileOutputStream(".keystore"); store.store(fo, password.toCharArray()); options.setKeyStoreOptions(new JksOptions().setPath(".keystore").setPassword(password)); options.setSsl(true); }
/** * * @param DN eg "CN=Test, L=Redmond, C=GB" * @param validity 24 * 60 * 60 is 1 Day * @return A private key and X509 certificate * @throws NoSuchAlgorithmException * @throws NoSuchProviderException * @throws InvalidKeyException * @throws IOException * @throws CertificateException * @throws SignatureException */ private CertKeyPair createCertAndKey(String DN, long validity) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, IOException, CertificateException, SignatureException { //Generate ROOT certificate CertAndKeyGen keyGen = new CertAndKeyGen("RSA", "SHA1WithRSA", null); keyGen.generate(1024); PrivateKey key = keyGen.getPrivateKey(); X509Certificate x509Certificate = keyGen.getSelfCertificate(new X500Name(DN), validity); return new CertKeyPair(key, x509Certificate); }