List of usage examples for org.bouncycastle.cert.jcajce JcaX509CertificateConverter JcaX509CertificateConverter
public JcaX509CertificateConverter()
From source file:org.kse.crypto.x509.X509CertificateGenerator.java
License:Open Source License
private X509Certificate generateVersion1(X500Name subject, X500Name issuer, Date validityStart, Date validityEnd, PublicKey publicKey, PrivateKey privateKey, SignatureType signatureType, BigInteger serialNumber) throws CryptoException { Date notBefore = validityStart == null ? new Date() : validityStart; Date notAfter = validityEnd == null ? new Date(notBefore.getTime() + TimeUnit.DAYS.toMillis(365)) : validityEnd;//www. jav a2s . c o m JcaX509v1CertificateBuilder certBuilder = new JcaX509v1CertificateBuilder(issuer, serialNumber, notBefore, notAfter, subject, publicKey); try { ContentSigner certSigner = new JcaContentSignerBuilder(signatureType.jce()).setProvider("BC") .build(privateKey); return new JcaX509CertificateConverter().setProvider("BC") .getCertificate(certBuilder.build(certSigner)); } catch (CertificateException ex) { throw new CryptoException(res.getString("CertificateGenFailed.exception.message"), ex); } catch (IllegalStateException ex) { throw new CryptoException(res.getString("CertificateGenFailed.exception.message"), ex); } catch (OperatorCreationException ex) { throw new CryptoException(res.getString("CertificateGenFailed.exception.message"), ex); } }
From source file:org.kse.crypto.x509.X509CertificateGenerator.java
License:Open Source License
private X509Certificate generateVersion3(X500Name subject, X500Name issuer, Date validityStart, Date validityEnd, PublicKey publicKey, PrivateKey privateKey, SignatureType signatureType, BigInteger serialNumber, X509Extension extensions, Provider provider) throws CryptoException, CertIOException { Date notBefore = validityStart == null ? new Date() : validityStart; Date notAfter = validityEnd == null ? new Date(notBefore.getTime() + TimeUnit.DAYS.toMillis(365)) : validityEnd;/*w ww .j av a 2 s . c o m*/ JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuer, serialNumber, notBefore, notAfter, subject, publicKey); if (extensions != null) { for (String oid : extensions.getCriticalExtensionOIDs()) { certBuilder.addExtension(new ASN1ObjectIdentifier(oid), true, getExtensionValue(extensions, oid)); } for (String oid : extensions.getNonCriticalExtensionOIDs()) { certBuilder.addExtension(new ASN1ObjectIdentifier(oid), false, getExtensionValue(extensions, oid)); } } try { ContentSigner certSigner = null; if (provider == null) { certSigner = new JcaContentSignerBuilder(signatureType.jce()).build(privateKey); } else { certSigner = new JcaContentSignerBuilder(signatureType.jce()).setProvider(provider) .build(privateKey); } return new JcaX509CertificateConverter().setProvider("BC") .getCertificate(certBuilder.build(certSigner)); } catch (CertificateException ex) { throw new CryptoException(res.getString("CertificateGenFailed.exception.message"), ex); } catch (IllegalStateException ex) { throw new CryptoException(res.getString("CertificateGenFailed.exception.message"), ex); } catch (OperatorCreationException ex) { throw new CryptoException(res.getString("CertificateGenFailed.exception.message"), ex); } }
From source file:org.loklak.LoklakInstallation.java
License:Open Source License
private static void setupHttpServer(int httpPort, int httpsPort) throws Exception { QueuedThreadPool pool = new QueuedThreadPool(); pool.setMaxThreads(500);//from ww w. ja v a2 s.c o m LoklakInstallation.server = new Server(pool); LoklakInstallation.server.setStopAtShutdown(true); //http if (!httpsMode.equals(HttpsMode.ONLY)) { HttpConfiguration http_config = new HttpConfiguration(); if (httpsMode.equals(HttpsMode.REDIRECT)) { //redirect http_config.addCustomizer(new SecureRequestCustomizer()); http_config.setSecureScheme("https"); http_config.setSecurePort(httpsPort); } ServerConnector connector = new ServerConnector(LoklakInstallation.server); connector.addConnectionFactory(new HttpConnectionFactory(http_config)); connector.setPort(httpPort); connector.setName("httpd:" + httpPort); connector.setIdleTimeout(20000); // timout in ms when no bytes send / received LoklakInstallation.server.addConnector(connector); } //https //uncommented lines for http2 (jetty 9.3 / java 8) if (httpsMode.isGreaterOrEqualTo(HttpsMode.ON)) { Log.getLog().info("HTTPS activated"); String keySource = DAO.getConfig("https.keysource", "keystore"); KeyStore keyStore; String keystoreManagerPass; //check for key source. Can be a java keystore or in pem format (gets converted automatically) if ("keystore".equals(keySource)) { Log.getLog().info("Loading keystore from disk"); //use native keystore format File keystoreFile = new File(DAO.conf_dir, DAO.getConfig("keystore.name", "keystore.jks")); if (!keystoreFile.exists() || !keystoreFile.isFile() || !keystoreFile.canRead()) { throw new Exception("Could not find keystore"); } keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(new FileInputStream(keystoreFile.getAbsolutePath()), DAO.getConfig("keystore.password", "").toCharArray()); keystoreManagerPass = DAO.getConfig("keystore.password", ""); } else if ("key-cert".equals(keySource)) { Log.getLog().info("Importing keystore from key/cert files"); //use more common pem format as used by openssl //generate random password char[] chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray(); StringBuilder sb = new StringBuilder(); Random random = new Random(); for (int i = 0; i < 20; i++) { char c = chars[random.nextInt(chars.length)]; sb.append(c); } String password = keystoreManagerPass = sb.toString(); //get key and cert File keyFile = new File(DAO.getConfig("https.key", "")); if (!keyFile.exists() || !keyFile.isFile() || !keyFile.canRead()) { throw new Exception("Could not find key file"); } File certFile = new File(DAO.getConfig("https.cert", "")); if (!certFile.exists() || !certFile.isFile() || !certFile.canRead()) { throw new Exception("Could not find cert file"); } Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); byte[] keyBytes = Files.readAllBytes(keyFile.toPath()); byte[] certBytes = Files.readAllBytes(certFile.toPath()); PEMParser parser = new PEMParser(new InputStreamReader(new ByteArrayInputStream(certBytes))); X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC") .getCertificate((X509CertificateHolder) parser.readObject()); parser = new PEMParser(new InputStreamReader(new ByteArrayInputStream(keyBytes))); PrivateKey key = new JcaPEMKeyConverter().setProvider("BC") .getPrivateKey((PrivateKeyInfo) parser.readObject()); keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null); keyStore.setCertificateEntry(cert.getSubjectX500Principal().getName(), cert); keyStore.setKeyEntry("defaultKey", key, password.toCharArray(), new Certificate[] { cert }); Log.getLog().info("Successfully imported keystore from key/cert files"); } else { throw new Exception("Invalid option for https.keysource"); } HttpConfiguration https_config = new HttpConfiguration(); https_config.addCustomizer(new SecureRequestCustomizer()); HttpConnectionFactory http1 = new HttpConnectionFactory(https_config); //HTTP2ServerConnectionFactory http2 = new HTTP2ServerConnectionFactory(https_config); //NegotiatingServerConnectionFactory.checkProtocolNegotiationAvailable(); //ALPNServerConnectionFactory alpn = new ALPNServerConnectionFactory(); //alpn.setDefaultProtocol(http1.getProtocol()); SslContextFactory sslContextFactory = new SslContextFactory(); sslContextFactory.setKeyStore(keyStore); sslContextFactory.setKeyManagerPassword(keystoreManagerPass); //sslContextFactory.setCipherComparator(HTTP2Cipher.COMPARATOR); //sslContextFactory.setUseCipherSuitesOrder(true); //SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, alpn.getProtocol()); SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, "http/1.1"); //ServerConnector sslConnector = new ServerConnector(LoklakServer.server, ssl, alpn, http2, http1); ServerConnector sslConnector = new ServerConnector(LoklakInstallation.server, ssl, http1); sslConnector.setPort(httpsPort); sslConnector.setName("httpd:" + httpsPort); sslConnector.setIdleTimeout(20000); // timout in ms when no bytes send / received LoklakInstallation.server.addConnector(sslConnector); } }
From source file:org.loklak.LoklakServer.java
License:Open Source License
private static void setupHttpServer(int httpPort, int httpsPort) throws Exception { QueuedThreadPool pool = new QueuedThreadPool(); pool.setMaxThreads(500);/*www .j a v a 2 s . c om*/ LoklakServer.server = new Server(pool); LoklakServer.server.setStopAtShutdown(true); //http if (!httpsMode.equals(HttpsMode.ONLY)) { HttpConfiguration http_config = new HttpConfiguration(); if (httpsMode.equals(HttpsMode.REDIRECT)) { //redirect http_config.addCustomizer(new SecureRequestCustomizer()); http_config.setSecureScheme("https"); http_config.setSecurePort(httpsPort); } ServerConnector connector = new ServerConnector(LoklakServer.server); connector.addConnectionFactory(new HttpConnectionFactory(http_config)); connector.setPort(httpPort); connector.setName("httpd:" + httpPort); connector.setIdleTimeout(20000); // timout in ms when no bytes send / received LoklakServer.server.addConnector(connector); } //https //uncommented lines for http2 (jetty 9.3 / java 8) if (httpsMode.isGreaterOrEqualTo(HttpsMode.ON)) { Log.getLog().info("HTTPS activated"); String keySource = DAO.getConfig("https.keysource", "keystore"); KeyStore keyStore; String keystoreManagerPass; //check for key source. Can be a java keystore or in pem format (gets converted automatically) if ("keystore".equals(keySource)) { Log.getLog().info("Loading keystore from disk"); //use native keystore format File keystoreFile = new File(DAO.conf_dir, DAO.getConfig("keystore.name", "keystore.jks")); if (!keystoreFile.exists() || !keystoreFile.isFile() || !keystoreFile.canRead()) { throw new Exception("Could not find keystore"); } keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(new FileInputStream(keystoreFile.getAbsolutePath()), DAO.getConfig("keystore.password", "").toCharArray()); keystoreManagerPass = DAO.getConfig("keystore.password", ""); } else if ("key-cert".equals(keySource)) { Log.getLog().info("Importing keystore from key/cert files"); //use more common pem format as used by openssl //generate random password char[] chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray(); StringBuilder sb = new StringBuilder(); Random random = new Random(); for (int i = 0; i < 20; i++) { char c = chars[random.nextInt(chars.length)]; sb.append(c); } String password = keystoreManagerPass = sb.toString(); //get key and cert File keyFile = new File(DAO.getConfig("https.key", "")); if (!keyFile.exists() || !keyFile.isFile() || !keyFile.canRead()) { throw new Exception("Could not find key file"); } File certFile = new File(DAO.getConfig("https.cert", "")); if (!certFile.exists() || !certFile.isFile() || !certFile.canRead()) { throw new Exception("Could not find cert file"); } Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); byte[] keyBytes = Files.readAllBytes(keyFile.toPath()); byte[] certBytes = Files.readAllBytes(certFile.toPath()); PEMParser parser = new PEMParser(new InputStreamReader(new ByteArrayInputStream(certBytes))); X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC") .getCertificate((X509CertificateHolder) parser.readObject()); parser = new PEMParser(new InputStreamReader(new ByteArrayInputStream(keyBytes))); PrivateKey key = new JcaPEMKeyConverter().setProvider("BC") .getPrivateKey((PrivateKeyInfo) parser.readObject()); keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null); keyStore.setCertificateEntry(cert.getSubjectX500Principal().getName(), cert); keyStore.setKeyEntry("defaultKey", key, password.toCharArray(), new Certificate[] { cert }); Log.getLog().info("Successfully imported keystore from key/cert files"); } else { throw new Exception("Invalid option for https.keysource"); } HttpConfiguration https_config = new HttpConfiguration(); https_config.addCustomizer(new SecureRequestCustomizer()); HttpConnectionFactory http1 = new HttpConnectionFactory(https_config); //HTTP2ServerConnectionFactory http2 = new HTTP2ServerConnectionFactory(https_config); //NegotiatingServerConnectionFactory.checkProtocolNegotiationAvailable(); //ALPNServerConnectionFactory alpn = new ALPNServerConnectionFactory(); //alpn.setDefaultProtocol(http1.getProtocol()); SslContextFactory sslContextFactory = new SslContextFactory(); sslContextFactory.setKeyStore(keyStore); sslContextFactory.setKeyManagerPassword(keystoreManagerPass); //sslContextFactory.setCipherComparator(HTTP2Cipher.COMPARATOR); //sslContextFactory.setUseCipherSuitesOrder(true); //SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, alpn.getProtocol()); SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, "http/1.1"); //ServerConnector sslConnector = new ServerConnector(LoklakServer.server, ssl, alpn, http2, http1); ServerConnector sslConnector = new ServerConnector(LoklakServer.server, ssl, http1); sslConnector.setPort(httpsPort); sslConnector.setName("httpd:" + httpsPort); sslConnector.setIdleTimeout(20000); // timout in ms when no bytes send / received LoklakServer.server.addConnector(sslConnector); } }
From source file:org.loklak.SusiInstallation.java
License:Open Source License
private static void setupHttpServer(int httpPort, int httpsPort) throws Exception { QueuedThreadPool pool = new QueuedThreadPool(); pool.setMaxThreads(500);/* w w w .ja va2 s . c om*/ SusiInstallation.server = new Server(pool); SusiInstallation.server.setStopAtShutdown(true); //http if (!httpsMode.equals(HttpsMode.ONLY)) { HttpConfiguration http_config = new HttpConfiguration(); if (httpsMode.equals(HttpsMode.REDIRECT)) { //redirect http_config.addCustomizer(new SecureRequestCustomizer()); http_config.setSecureScheme("https"); http_config.setSecurePort(httpsPort); } ServerConnector connector = new ServerConnector(SusiInstallation.server); connector.addConnectionFactory(new HttpConnectionFactory(http_config)); connector.setPort(httpPort); connector.setName("httpd:" + httpPort); connector.setIdleTimeout(20000); // timout in ms when no bytes send / received SusiInstallation.server.addConnector(connector); } //https //uncommented lines for http2 (jetty 9.3 / java 8) if (httpsMode.isGreaterOrEqualTo(HttpsMode.ON)) { Log.getLog().info("HTTPS activated"); String keySource = DAO.getConfig("https.keysource", "keystore"); KeyStore keyStore; String keystoreManagerPass; //check for key source. Can be a java keystore or in pem format (gets converted automatically) if ("keystore".equals(keySource)) { Log.getLog().info("Loading keystore from disk"); //use native keystore format File keystoreFile = new File(DAO.conf_dir, DAO.getConfig("keystore.name", "keystore.jks")); if (!keystoreFile.exists() || !keystoreFile.isFile() || !keystoreFile.canRead()) { throw new Exception("Could not find keystore"); } keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(new FileInputStream(keystoreFile.getAbsolutePath()), DAO.getConfig("keystore.password", "").toCharArray()); keystoreManagerPass = DAO.getConfig("keystore.password", ""); } else if ("key-cert".equals(keySource)) { Log.getLog().info("Importing keystore from key/cert files"); //use more common pem format as used by openssl //generate random password char[] chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray(); StringBuilder sb = new StringBuilder(); Random random = new Random(); for (int i = 0; i < 20; i++) { char c = chars[random.nextInt(chars.length)]; sb.append(c); } String password = keystoreManagerPass = sb.toString(); //get key and cert File keyFile = new File(DAO.getConfig("https.key", "")); if (!keyFile.exists() || !keyFile.isFile() || !keyFile.canRead()) { throw new Exception("Could not find key file"); } File certFile = new File(DAO.getConfig("https.cert", "")); if (!certFile.exists() || !certFile.isFile() || !certFile.canRead()) { throw new Exception("Could not find cert file"); } Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); byte[] keyBytes = Files.readAllBytes(keyFile.toPath()); byte[] certBytes = Files.readAllBytes(certFile.toPath()); PEMParser parser = new PEMParser(new InputStreamReader(new ByteArrayInputStream(certBytes))); X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC") .getCertificate((X509CertificateHolder) parser.readObject()); parser = new PEMParser(new InputStreamReader(new ByteArrayInputStream(keyBytes))); PrivateKey key = new JcaPEMKeyConverter().setProvider("BC") .getPrivateKey((PrivateKeyInfo) parser.readObject()); keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null); keyStore.setCertificateEntry(cert.getSubjectX500Principal().getName(), cert); keyStore.setKeyEntry("defaultKey", key, password.toCharArray(), new Certificate[] { cert }); Log.getLog().info("Successfully imported keystore from key/cert files"); } else { throw new Exception("Invalid option for https.keysource"); } HttpConfiguration https_config = new HttpConfiguration(); https_config.addCustomizer(new SecureRequestCustomizer()); HttpConnectionFactory http1 = new HttpConnectionFactory(https_config); //HTTP2ServerConnectionFactory http2 = new HTTP2ServerConnectionFactory(https_config); //NegotiatingServerConnectionFactory.checkProtocolNegotiationAvailable(); //ALPNServerConnectionFactory alpn = new ALPNServerConnectionFactory(); //alpn.setDefaultProtocol(http1.getProtocol()); SslContextFactory sslContextFactory = new SslContextFactory(); sslContextFactory.setKeyStore(keyStore); sslContextFactory.setKeyManagerPassword(keystoreManagerPass); //sslContextFactory.setCipherComparator(HTTP2Cipher.COMPARATOR); //sslContextFactory.setUseCipherSuitesOrder(true); //SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, alpn.getProtocol()); SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, "http/1.1"); ServerConnector sslConnector = new ServerConnector(SusiInstallation.server, ssl, http1); sslConnector.setPort(httpsPort); sslConnector.setName("httpd:" + httpsPort); sslConnector.setIdleTimeout(20000); // timout in ms when no bytes send / received SusiInstallation.server.addConnector(sslConnector); } }
From source file:org.metaeffekt.dcc.agent.AuthenticationKeyGenerator.java
License:Apache License
private X509Certificate generateCertificate(KeyPair key, String certificateCN, Date begin, Date end) throws GeneralSecurityException, IOException, OperatorException { final X500NameBuilder nameBuilder = new X500NameBuilder(); nameBuilder.addRDN(BCStyle.CN, certificateCN); final X500Name name = nameBuilder.build(); final JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(name, new BigInteger(String.valueOf(random.nextInt())), begin, end, name, key.getPublic()); certBuilder.addExtension(Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(key.getPublic())); final X509CertificateHolder certificateHolder = certBuilder .build(new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).build(key.getPrivate())); final X509Certificate certificate = new JcaX509CertificateConverter().getCertificate(certificateHolder); return certificate; }
From source file:org.metaeffekt.dcc.commons.pki.CertificateManager.java
License:Apache License
private X509Certificate generateCertificate() throws GeneralSecurityException, IOException, OperatorException { String issuerComponentName = getIssuerComponentName(); // determine signer; per default issuer is signer (issuer can be subject --> self-signed) String signerComponentName = getSignerComponentName(issuerComponentName); if (signerComponentName.equals(componentName)) { // self-signed certs is not our goal if (BOOLEAN_STRING_FALSE.equals(getProperty(PROPERTY_CERT_SELFSIGNED, BOOLEAN_STRING_FALSE))) { return null; }// w w w .j a v a 2s.c o m } PublicKey publicKey = loadPublicKey(); final Calendar begin = getValidityPeriodBegin(); final Calendar end = getValidityPeriodEnd(begin); final X500Name name = createSubjectNameBuilder(); final BigInteger serialNo = new BigInteger(String.valueOf(random.nextInt())); JcaX509v3CertificateBuilder certBuilder = null; X509Certificate issuerCertificate = null; if (issuerComponentName.equals(componentName)) { // check whether this and the issuer are the same and user the already constructed name if (issuerComponentName.equals(componentName)) { certBuilder = new JcaX509v3CertificateBuilder(name, serialNo, begin.getTime(), end.getTime(), name, publicKey); } } else { // lookup the certificate of the referenced issuer File issuerDir = new File(componentBaseDir, issuerComponentName); File issuerCert = new File(issuerDir, FILENAME_CERT); if (issuerCert.exists()) { issuerCertificate = (X509Certificate) KeyUtils.loadCertificate(issuerCert.getPath()); certBuilder = new JcaX509v3CertificateBuilder(issuerCertificate, serialNo, begin.getTime(), end.getTime(), name, publicKey); } } if (certBuilder == null) { // issuer cert was not found. Potentially it was not yet created return null; } List<Extension> extensions = createExtensions(publicKey, issuerCertificate); for (Extension extension : extensions) { certBuilder.addExtension(extension); } // load the private key of the signer (signer may be issuer, may be self) PrivateKey signerPrivateKey = null; File signerDir = new File(componentBaseDir, signerComponentName); File signerPrivateKeyFile = new File(signerDir, FILENAME_PRIVATE_KEY); if (signerPrivateKeyFile.exists()) { signerPrivateKey = KeyUtils.loadKey(signerPrivateKeyFile.getPath()); } else { // when we cannot access the signer we cannot provide a certificate return null; } final String signatureAlgorithm = getProperty(PROPERTY_CERT_SIGNATURE_ALGORITHM, DEFAULT_SIGNING_ALGORITHM); final X509CertificateHolder certificateHolder = certBuilder .build(new JcaContentSignerBuilder(signatureAlgorithm).build(signerPrivateKey)); return new JcaX509CertificateConverter().getCertificate(certificateHolder); }
From source file:org.metaeffekt.dcc.commons.pki.KeyUtils.java
License:Apache License
public static Certificate loadCertificate(String file) throws IOException, CertificateException { PEMParser parser = new PEMParser(new FileReader(file)); try {/*from w ww . j a v a 2 s . co m*/ X509CertificateHolder holder = (X509CertificateHolder) parser.readObject(); JcaX509CertificateConverter converter = new JcaX509CertificateConverter(); return converter.getCertificate(holder); } finally { IOUtils.closeQuietly(parser); } }
From source file:org.moxie.proxy.MakeCertificate.java
License:Apache License
public static void generateSelfSignedCertificate(String hostname, File keystore, String keystorePassword) { try {//w w w . j av a 2 s . c o m Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", "BC"); kpGen.initialize(1024, new SecureRandom()); KeyPair pair = kpGen.generateKeyPair(); // Generate self-signed certificate X500NameBuilder builder = new X500NameBuilder(BCStyle.INSTANCE); builder.addRDN(BCStyle.OU, Constants.getName()); builder.addRDN(BCStyle.O, Constants.getName()); builder.addRDN(BCStyle.CN, hostname); Date notBefore = new Date(System.currentTimeMillis() - ONEDAY); Date notAfter = new Date(System.currentTimeMillis() + 10 * ONEYEAR); BigInteger serial = BigInteger.valueOf(System.currentTimeMillis()); X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(builder.build(), serial, notBefore, notAfter, builder.build(), pair.getPublic()); ContentSigner sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider(BC) .build(pair.getPrivate()); X509Certificate cert = new JcaX509CertificateConverter().setProvider(BC) .getCertificate(certGen.build(sigGen)); cert.checkValidity(new Date()); cert.verify(cert.getPublicKey()); // Save to keystore KeyStore store = KeyStore.getInstance("JKS"); if (keystore.exists()) { FileInputStream fis = new FileInputStream(keystore); store.load(fis, keystorePassword.toCharArray()); fis.close(); } else { store.load(null); } store.setKeyEntry(hostname, pair.getPrivate(), keystorePassword.toCharArray(), new java.security.cert.Certificate[] { cert }); FileOutputStream fos = new FileOutputStream(keystore); store.store(fos, keystorePassword.toCharArray()); fos.close(); } catch (Throwable t) { t.printStackTrace(); throw new RuntimeException("Failed to generate self-signed certificate!", t); } }
From source file:org.moxie.proxy.MakeCertificate.java
License:Apache License
public static void generateSelfSignedCertificate(String hostname, File keystore, String keystorePassword, String info) {//w ww . jav a 2s .c om try { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", "BC"); kpGen.initialize(1024, new SecureRandom()); KeyPair pair = kpGen.generateKeyPair(); // Generate self-signed certificate X500Principal principal = new X500Principal(info); Date notBefore = new Date(System.currentTimeMillis() - ONEDAY); Date notAfter = new Date(System.currentTimeMillis() + 10 * ONEYEAR); BigInteger serial = BigInteger.valueOf(System.currentTimeMillis()); X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(principal, serial, notBefore, notAfter, principal, pair.getPublic()); ContentSigner sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider(BC) .build(pair.getPrivate()); X509Certificate cert = new JcaX509CertificateConverter().setProvider(BC) .getCertificate(certGen.build(sigGen)); cert.checkValidity(new Date()); cert.verify(cert.getPublicKey()); // Save to keystore KeyStore store = KeyStore.getInstance("JKS"); if (keystore.exists()) { FileInputStream fis = new FileInputStream(keystore); store.load(fis, keystorePassword.toCharArray()); fis.close(); } else { store.load(null); } store.setKeyEntry(hostname, pair.getPrivate(), keystorePassword.toCharArray(), new java.security.cert.Certificate[] { cert }); FileOutputStream fos = new FileOutputStream(keystore); store.store(fos, keystorePassword.toCharArray()); fos.close(); } catch (Throwable t) { t.printStackTrace(); throw new RuntimeException("Failed to generate self-signed certificate!", t); } }