List of usage examples for java.security KeyStore load
public final void load(InputStream stream, char[] password) throws IOException, NoSuchAlgorithmException, CertificateException
From source file:com.arm.connector.bridge.core.Utils.java
public static String createKeystore(ErrorLogger logger, String base, String sep, String filename, X509Certificate cert, PrivateKey priv_key, String pw) { String basedir = base + File.separator + sep; String keystore_filename = basedir + File.separator + filename; try {//from w w w. j a v a2s . c o m // first create the directory if it does not exist File file = new File(basedir); // make the directories logger.info("createKeystore: Making directories for keystore..."); file.mkdirs(); // create the KeyStore logger.info("createKeystore: Creating keystore: " + keystore_filename); file = new File(keystore_filename); if (file.createNewFile()) { logger.info("createKeystore: keystore created: " + keystore_filename); } else { logger.warning("createKeystore: keystore already exists " + keystore_filename); } // store data into the keystore KeyStore ks = KeyStore.getInstance("JKS"); ks.load(null, pw.toCharArray()); // set the certificate, priv and pub keys if (cert != null) { Certificate[] cert_list = new Certificate[2]; cert_list[0] = cert; cert_list[1] = Utils.createCACertificate(logger); ks.setCertificateEntry("aws", cert_list[0]); ks.setCertificateEntry("verisign", cert_list[1]); if (priv_key != null) { try { ks.setKeyEntry("privkey", priv_key, pw.toCharArray(), cert_list); } catch (Exception ex2) { logger.warning("createKeystore: Exception during priv addition... not added to keystore", ex2); } } else { logger.warning("createKeystore: privkey is NULL... not added to keystore"); } } else { logger.warning("createKeystore: certificate is NULL... not added to keystore"); } try (FileOutputStream fos = new FileOutputStream(keystore_filename)) { // store away the keystore content ks.store(fos, pw.toCharArray()); // close fos.flush(); } } catch (IOException | KeyStoreException | NoSuchAlgorithmException | CertificateException ex) { logger.warning("createKeystore: Unable to create keystore: " + keystore_filename, ex); } // return the keystore filename return keystore_filename; }
From source file:com.vmware.photon.controller.core.Main.java
private static PhotonControllerXenonHost startXenonHost(PhotonControllerConfig photonControllerConfig, ThriftModule thriftModule, DeployerConfig deployerConfig, SSLContext sslContext) throws Throwable { // Values for CloudStore final HostClientFactory hostClientFactory = thriftModule.getHostClientFactory(); final AgentControlClientFactory agentControlClientFactory = thriftModule.getAgentControlClientFactory(); final NsxClientFactory nsxClientFactory = new NsxClientFactory(); // Values for Scheduler final ServerSet cloudStoreServerSet = new StaticServerSet( new InetSocketAddress(photonControllerConfig.getXenonConfig().getRegistrationAddress(), Constants.PHOTON_CONTROLLER_PORT)); final CloudStoreHelper cloudStoreHelper = new CloudStoreHelper(cloudStoreServerSet); final CloseableHttpAsyncClient httpClient; try {//w ww .j a va 2s . c o m SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial((chain, authtype) -> true).build(); httpClient = HttpAsyncClientBuilder.create() .setHostnameVerifier(SSLIOSessionStrategy.ALLOW_ALL_HOSTNAME_VERIFIER).setSSLContext(sslcontext) .build(); httpClient.start(); } catch (Throwable e) { throw new RuntimeException(e); } ServerSet apiFeServerSet = new StaticServerSet(new InetSocketAddress( photonControllerConfig.getXenonConfig().getRegistrationAddress(), Constants.MANAGEMENT_API_PORT)); logger.info("Creating PhotonController Xenon Host"); final PhotonControllerXenonHost photonControllerXenonHost = new PhotonControllerXenonHost( photonControllerConfig.getXenonConfig(), hostClientFactory, agentControlClientFactory, nsxClientFactory, cloudStoreHelper, sslContext); logger.info("Created PhotonController Xenon Host"); // Set referer Uri from the xenon host, because we do not want to rely on // CloudStoreHelper's default mechanise to create referer based on local address, // because CloudStoreHelper uses InetAddress.getLocalHost() which depends on // /etc/hosts having a hostname entry, which is not always available. // This change will allow people to run this service without need to // update their /etc/hosts file. cloudStoreHelper.setRefererUri(photonControllerXenonHost.getUri()); final ConstraintChecker checker = new CloudStoreConstraintChecker(cloudStoreHelper, photonControllerXenonHost); logger.info("Creating Cloud Store Xenon Service Group"); CloudStoreServiceGroup cloudStoreServiceGroup = createCloudStoreServiceGroup(deployerConfig.isInstaller()); logger.info("Created Cloud Store Xenon Service Group"); logger.info("Registering Cloud Store Xenon Service Group"); photonControllerXenonHost.registerCloudStore(cloudStoreServiceGroup); logger.info("Registered Cloud Store Xenon Service Group"); logger.info("Creating Scheduler Xenon Service Group"); SchedulerServiceGroup schedulerServiceGroup = createSchedulerServiceGroup(photonControllerConfig.getRoot(), checker); logger.info("Created Scheduler Xenon Service Group"); logger.info("Registering Scheduler Xenon Service Group"); photonControllerXenonHost.registerScheduler(schedulerServiceGroup); logger.info("Registered Scheduler Xenon Service Group"); logger.info("Creating Housekeeper Xenon Service Group"); HousekeeperServiceGroup housekeeperServiceGroup = createHousekeeperServiceGroup(); logger.info("Created Housekeeper Xenon Service Group"); logger.info("Registering Housekeeper Xenon Service Group"); photonControllerXenonHost.registerHousekeeper(housekeeperServiceGroup); logger.info("Registered Housekeeper Xenon Service Group"); logger.info("Creating Deployer Xenon Service Group"); DeployerServiceGroup deployerServiceGroup = createDeployerServiceGroup(photonControllerConfig, deployerConfig, apiFeServerSet, cloudStoreServerSet, httpClient); logger.info("Created Deployer Xenon Service Group"); logger.info("Registering Deployer Xenon Service Group"); photonControllerXenonHost.registerDeployer(deployerServiceGroup); logger.info("Registered Deployer Xenon Service Group"); DeployerContext deployerContext = deployerConfig.getDeployerContext(); if (deployerContext.isAuthEnabled()) { ServiceClient serviceClient = NettyHttpServiceClient.create(Main.class.getSimpleName(), Executors.newFixedThreadPool(Utils.DEFAULT_THREAD_COUNT), Executors.newScheduledThreadPool(Utils.DEFAULT_IO_THREAD_COUNT), photonControllerXenonHost); /* To make sure that Xenon uses only TLSv1.2 and disallows SSLv3, TLSv1, TLSv1.1 the Docker file for the photon-controller-core container is edited. The java.security file located inside the container at the location /var/opt/OpenJDK-* /jre/lib/security has the information under the jdk.tls.disabledAlgorithms */ SSLContext clientContext = SSLContext.getInstance(ServiceClient.TLS_PROTOCOL_NAME); TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init((KeyStore) null); KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); KeyStore keyStore = KeyStore.getInstance("JKS"); try (FileInputStream fis = new FileInputStream(deployerContext.getKeyStorePath())) { keyStore.load(fis, deployerContext.getKeyStorePassword().toCharArray()); } keyManagerFactory.init(keyStore, deployerContext.getKeyStorePassword().toCharArray()); clientContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); serviceClient.setSSLContext(clientContext); photonControllerXenonHost.setClient(serviceClient); } logger.info("Starting PhotonController Xenon Host"); photonControllerXenonHost.start(); logger.info("Started PhotonController Xenon Host"); logger.info("Creating SystemConfig instance"); SystemConfig.createInstance(photonControllerXenonHost); logger.info("Created SystemConfig instance"); return photonControllerXenonHost; }
From source file:org.apache.cxf.fediz.integrationtests.KerberosTest.java
public static String sendHttpGet(String url, String ticket, int returnCodeIDP, int returnCodeRP, int idpPort) throws Exception { CloseableHttpClient httpClient = null; try {//from w w w . j av a 2s.c o m KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream instream = new FileInputStream(new File("./target/test-classes/client.jks")); try { trustStore.load(instream, "clientpass".toCharArray()); } finally { try { instream.close(); } catch (Exception ex) { ex.printStackTrace(); } } SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); sslContextBuilder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()); sslContextBuilder.loadKeyMaterial(trustStore, "clientpass".toCharArray()); SSLContext sslContext = sslContextBuilder.build(); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); httpClientBuilder.setSSLSocketFactory(sslSocketFactory); httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy()); httpClient = httpClientBuilder.build(); HttpGet httpget = new HttpGet(url); httpget.addHeader("Authorization", "Negotiate " + ticket); HttpResponse response = httpClient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } Assert.assertTrue("IDP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: " + returnCodeIDP + "]", returnCodeIDP == response.getStatusLine().getStatusCode()); if (response.getStatusLine().getStatusCode() != 200) { return null; } // Redirect to a POST is not supported without user interaction // http://www.ietf.org/rfc/rfc2616.txt // If the 301 status code is received in response to a request other // than GET or HEAD, the user agent MUST NOT automatically redirect the // request unless it can be confirmed by the user, since this might // change the conditions under which the request was issued. Source source = new Source(EntityUtils.toString(entity)); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); FormFields formFields = source.getFormFields(); List<Element> forms = source.getAllElements(HTMLElementName.FORM); Assert.assertEquals("Only one form expected but got " + forms.size(), 1, forms.size()); String postUrl = forms.get(0).getAttributeValue("action"); Assert.assertNotNull("Form field 'wa' not found", formFields.get("wa")); Assert.assertNotNull("Form field 'wresult' not found", formFields.get("wresult")); for (FormField formField : formFields) { if (formField.getUserValueCount() != 0) { nvps.add(new BasicNameValuePair(formField.getName(), formField.getValues().get(0))); } } HttpPost httppost = new HttpPost(postUrl); httppost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); response = httpClient.execute(httppost); entity = response.getEntity(); System.out.println(response.getStatusLine()); Assert.assertTrue("RP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: " + returnCodeRP + "]", returnCodeRP == response.getStatusLine().getStatusCode()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } return EntityUtils.toString(entity); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources if (httpClient != null) { httpClient.close(); } } }
From source file:com.piusvelte.taplock.server.TapLockServer.java
protected static SecretKey getSecretKey(KeyStore ks) { SecretKey sk = null;/*w ww .j a v a2 s .c om*/ if (ks != null) { boolean ksLoaded = false; try { ks.load(new FileInputStream(sKeystore), sPassphrase.toCharArray()); ksLoaded = true; } catch (NoSuchAlgorithmException e) { writeLog("getSecretKey: " + e.getMessage()); } catch (CertificateException e) { writeLog("getSecretKey: " + e.getMessage()); } catch (FileNotFoundException e) { writeLog("getSecretKey: " + e.getMessage()); } catch (IOException e) { writeLog("getSecretKey: " + e.getMessage()); } if (ksLoaded) { try { sk = (SecretKey) ks.getKey(TAP_LOCK, sPassphrase.toCharArray()); } catch (UnrecoverableKeyException e) { writeLog("getSecretKey: " + e.getMessage()); } catch (KeyStoreException e) { writeLog("getSecretKey: " + e.getMessage()); } catch (NoSuchAlgorithmException e) { writeLog("getSecretKey: " + e.getMessage()); } } } return sk; }
From source file:com.vangent.hieos.services.sts.util.STSUtil.java
/** * * @param stsConfig/*from www . j ava2s .co m*/ * @return * @throws STSException */ public static KeyStore getKeyStore(STSConfig stsConfig) throws STSException { KeyStore ks; try { ks = KeyStore.getInstance(KeyStore.getDefaultType()); String keyStorePassword = stsConfig.getKeyStorePassword(); char[] password = keyStorePassword.toCharArray(); FileInputStream fis = new FileInputStream(stsConfig.getKeyStoreFileName()); ks.load(fis, password); fis.close(); } catch (Exception ex) { throw new STSException("Problem loading keystore: " + ex.getMessage()); } return ks; }
From source file:com.aware.ui.Plugins_Manager.java
/** * Downloads and compresses image for optimized icon caching * @param image_url//w w w. j a v a 2 s . c o m * @return */ public static byte[] cacheImage(String image_url, Context sContext) { try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream caInput = sContext.getResources().openRawResource(R.raw.aware); Certificate ca; try { ca = cf.generateCertificate(caInput); } finally { caInput.close(); } KeyStore sKeyStore = KeyStore.getInstance(KeyStore.getDefaultType()); InputStream inStream = sContext.getResources().openRawResource(R.raw.awareframework); sKeyStore.load(inStream, "awareframework".toCharArray()); inStream.close(); sKeyStore.setCertificateEntry("ca", ca); String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(sKeyStore); SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); //Fetch image now that we recognise SSL URL image_path = new URL(image_url.replace("http://", "https://")); //make sure we are fetching the images over https HttpsURLConnection image_connection = (HttpsURLConnection) image_path.openConnection(); image_connection.setSSLSocketFactory(context.getSocketFactory()); InputStream in_stream = image_connection.getInputStream(); Bitmap tmpBitmap = BitmapFactory.decodeStream(in_stream); ByteArrayOutputStream output = new ByteArrayOutputStream(); tmpBitmap.compress(Bitmap.CompressFormat.PNG, 100, output); return output.toByteArray(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (CertificateException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } return null; }
From source file:com.vangent.hieos.services.sts.util.STSUtil.java
/** * // w w w .j ava 2 s. c o m * @param stsConfig * @return * @throws STSException */ public static KeyStore getTrustStore(STSConfig stsConfig) throws STSException { KeyStore ks; try { ks = KeyStore.getInstance(KeyStore.getDefaultType()); String trustStorePassword = stsConfig.getTrustStorePassword(); char[] password = trustStorePassword.toCharArray(); FileInputStream fis = new FileInputStream(stsConfig.getTrustStoreFileName()); ks.load(fis, password); fis.close(); } catch (Exception ex) { throw new STSException("Problem loading truststore: " + ex.getMessage()); } return ks; }
From source file:ddf.security.sts.claimsHandler.ClaimsHandlerManager.java
public static KeyManagerFactory createKeyManagerFactory(String keyStoreLoc, String keyStorePass) throws IOException { KeyManagerFactory kmf;/* w w w. ja va 2 s .c om*/ try { // keystore stuff KeyStore keyStore = KeyStore.getInstance(System.getProperty("javax.net.ssl.keyStoreType")); LOGGER.debug("keyStoreLoc = {}", keyStoreLoc); FileInputStream keyFIS = new FileInputStream(keyStoreLoc); try { LOGGER.debug("Loading keyStore"); keyStore.load(keyFIS, keyStorePass.toCharArray()); } catch (CertificateException e) { throw new IOException("Unable to load certificates from keystore. " + keyStoreLoc, e); } finally { IOUtils.closeQuietly(keyFIS); } kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(keyStore, keyStorePass.toCharArray()); LOGGER.debug("key manager factory initialized"); } catch (NoSuchAlgorithmException e) { throw new IOException( "Problems creating SSL socket. Usually this is " + "referring to the certificate sent by the server not being trusted by the client.", e); } catch (UnrecoverableKeyException e) { throw new IOException("Unable to load keystore. " + keyStoreLoc, e); } catch (KeyStoreException e) { throw new IOException("Unable to read keystore. " + keyStoreLoc, e); } return kmf; }
From source file:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImplIT.java
/** * @throws java.lang.Exception/*from w ww . j a va2 s . co m*/ */ @BeforeClass @Ignore public static void setUpBeforeCLass() throws Exception { Security.addProvider(new BouncyCastleProvider()); // Create some test username and passwords for services serviceURI = new URI("http://someservice"); usernamePassword = new UsernamePassword("testuser", "testpasswd"); serviceURI2 = new URI("http://someservice2"); usernamePassword2 = new UsernamePassword("testuser2", "testpasswd2"); serviceURI3 = new URI("http://someservice3"); usernamePassword3 = new UsernamePassword("testuser3", "testpasswd3"); // Load the test private key and its certificate File privateKeyCertFile = new File(privateKeyFileURL.getPath()); KeyStore pkcs12Keystore = java.security.KeyStore.getInstance("PKCS12", "BC"); // We have to use the BC provider here as the certificate chain is not loaded if we use whichever provider is first in Java!!! FileInputStream inStream = new FileInputStream(privateKeyCertFile); pkcs12Keystore.load(inStream, privateKeyAndPKCS12KeystorePassword.toCharArray()); // KeyStore pkcs12Keystore = credentialManager.loadPKCS12Keystore(privateKeyCertFile, privateKeyPassword); Enumeration<String> aliases = pkcs12Keystore.aliases(); while (aliases.hasMoreElements()) { // The test-private-key-cert.p12 file contains only one private key // and corresponding certificate entry String alias = aliases.nextElement(); if (pkcs12Keystore.isKeyEntry(alias)) { // is it a (private) key entry? privateKey = pkcs12Keystore.getKey(alias, privateKeyAndPKCS12KeystorePassword.toCharArray()); privateKeyCertChain = pkcs12Keystore.getCertificateChain(alias); break; } } inStream.close(); // Load the test trusted certificate (belonging to *.Google.com) File trustedCertFile = new File(trustedCertficateGoogleFileURL.getPath()); inStream = new FileInputStream(trustedCertFile); CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); trustedCertficateGoogle = (X509Certificate) certFactory.generateCertificate(inStream); try { inStream.close(); } catch (Exception e) { // Ignore } // Load the test trusted certificate (belonging to heater.cs.man.ac.uk) File trustedCertFile2 = new File(trustedCertficateHeaterFileURL.getPath()); inStream = new FileInputStream(trustedCertFile2); trustedCertficateHeater = (X509Certificate) certFactory.generateCertificate(inStream); try { inStream.close(); } catch (Exception e) { // Ignore } credentialManager = new CredentialManagerImpl(); // // The code below sets up the Keystore and Truststore files and loads some data into them // // and saves them into a temp directory. These files can later be used for testing the Credential // // Manager with non-empty keystores. // Random randomGenerator = new Random(); // String credentialManagerDirectoryPath = System // .getProperty("java.io.tmpdir") // + System.getProperty("file.separator") // + "taverna-security-" // + randomGenerator.nextInt(1000000); // System.out.println("Credential Manager's directory path: " // + credentialManagerDirectoryPath); // credentialManagerDirectory = new File(credentialManagerDirectoryPath); // credentialManager.setConfigurationDirectoryPath(credentialManagerDirectory); // // // Create the dummy master password provider // masterPasswordProvider = new DummyMasterPasswordProvider(); // masterPasswordProvider.setMasterPassword(masterPassword); // List<MasterPasswordProvider> masterPasswordProviders = new ArrayList<MasterPasswordProvider>(); // masterPasswordProviders.add(masterPasswordProvider); // credentialManager.setMasterPasswordProviders(masterPasswordProviders); // // // Add some stuff into Credential Manager // credentialManager.addUsernameAndPasswordForService(usernamePassword, serviceURI); // credentialManager.addUsernameAndPasswordForService(usernamePassword2, serviceURI2); // credentialManager.addUsernameAndPasswordForService(usernamePassword3, serviceURI3); // credentialManager.addKeyPair(privateKey, privateKeyCertChain); // credentialManager.addTrustedCertificate(trustedCertficate); // Set up a random temp directory and copy the test keystore files // from resources/security Random randomGenerator = new Random(); String credentialManagerDirectoryPath = System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + "taverna-security-" + randomGenerator.nextInt(1000000); System.out.println("Credential Manager's directory path: " + credentialManagerDirectoryPath); credentialManagerDirectory = new File(credentialManagerDirectoryPath); if (!credentialManagerDirectory.exists()) { credentialManagerDirectory.mkdir(); } URL keystoreFileURL = CredentialManagerImplIT.class.getResource("/security/t2keystore.ubr"); File keystoreFile = new File(keystoreFileURL.getPath()); File keystoreDestFile = new File(credentialManagerDirectory, "taverna-keystore.ubr"); URL truststroreFileURL = CredentialManagerImplIT.class.getResource("/security/t2truststore.ubr"); File truststoreFile = new File(truststroreFileURL.getPath()); File truststoreDestFile = new File(credentialManagerDirectory, "taverna-truststore.ubr"); FileUtils.copyFile(keystoreFile, keystoreDestFile); FileUtils.copyFile(truststoreFile, truststoreDestFile); credentialManager.setConfigurationDirectoryPath(credentialManagerDirectory); // Create the dummy master password provider masterPasswordProvider = new DummyMasterPasswordProvider(); masterPasswordProvider.setMasterPassword(masterPassword); List<MasterPasswordProvider> masterPasswordProviders = new ArrayList<MasterPasswordProvider>(); masterPasswordProviders.add(masterPasswordProvider); credentialManager.setMasterPasswordProviders(masterPasswordProviders); // Set an empty list for trust confirmation providers credentialManager.setTrustConfirmationProviders(new ArrayList<TrustConfirmationProvider>()); keystoreChangedObserver = new Observer<KeystoreChangedEvent>() { @Override public void notify(Observable<KeystoreChangedEvent> sender, KeystoreChangedEvent message) throws Exception { // TODO Auto-generated method stub } }; credentialManager.addObserver(keystoreChangedObserver); }
From source file:strat.mining.stratum.proxy.Launcher.java
/** * Check that a valid SSl certificate already exists. If not, create a new * one.//from w w w. ja v a 2s . c om * * @throws Exception */ private static void checkCertificate() throws Exception { File storeFile = new File(ConfigurationManager.getInstance().getDatabaseDirectory(), KEYSTORE_FILE_NAME); KeyStore keyStore = KeyStore.getInstance("JKS"); if (!storeFile.exists()) { LOGGER.info("KeyStore does not exist. Create {}", storeFile.getAbsolutePath()); storeFile.getParentFile().mkdirs(); storeFile.createNewFile(); keyStore.load(null, null); LOGGER.info("Generating new SSL certificate."); AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256withRSA"); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); RSAKeyPairGenerator keyGenerator = new RSAKeyPairGenerator(); keyGenerator .init(new RSAKeyGenerationParameters(BigInteger.valueOf(101), new SecureRandom(), 2048, 14)); AsymmetricCipherKeyPair keysPair = keyGenerator.generateKeyPair(); RSAKeyParameters rsaPrivateKey = (RSAKeyParameters) keysPair.getPrivate(); RSAPrivateKeySpec rsaPrivSpec = new RSAPrivateKeySpec(rsaPrivateKey.getModulus(), rsaPrivateKey.getExponent()); RSAKeyParameters rsaPublicKey = (RSAKeyParameters) keysPair.getPublic(); RSAPublicKeySpec rsaPublicSpec = new RSAPublicKeySpec(rsaPublicKey.getModulus(), rsaPublicKey.getExponent()); KeyFactory kf = KeyFactory.getInstance("RSA"); PrivateKey rsaPriv = kf.generatePrivate(rsaPrivSpec); PublicKey rsaPub = kf.generatePublic(rsaPublicSpec); X500Name issuerDN = new X500Name("CN=localhost, OU=None, O=None, L=None, C=None"); Integer randomNumber = new SecureRandom().nextInt(); BigInteger serialNumber = BigInteger.valueOf(randomNumber >= 0 ? randomNumber : randomNumber * -1); Date notBefore = new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30); Date notAfter = new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)); X500Name subjectDN = new X500Name("CN=localhost, OU=None, O=None, L=None, C=None"); byte[] publickeyb = rsaPub.getEncoded(); ASN1Sequence sequence = (ASN1Sequence) ASN1Primitive.fromByteArray(publickeyb); SubjectPublicKeyInfo subPubKeyInfo = new SubjectPublicKeyInfo(sequence); X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder(issuerDN, serialNumber, notBefore, notAfter, subjectDN, subPubKeyInfo); ContentSigner contentSigner = new BcRSAContentSignerBuilder(sigAlgId, digAlgId) .build(keysPair.getPrivate()); X509CertificateHolder certificateHolder = v3CertGen.build(contentSigner); Certificate certificate = new CertificateFactory() .engineGenerateCertificate(new ByteBufferBackedInputStream( ByteBuffer.wrap(certificateHolder.toASN1Structure().getEncoded()))); LOGGER.info("Certificate generated."); keyStore.setKeyEntry(KEYSTORE_KEY_ENTRY_ALIAS, rsaPriv, KEYSTORE_PASSWORD.toCharArray(), new java.security.cert.Certificate[] { certificate }); keyStore.store(new FileOutputStream(storeFile), KEYSTORE_PASSWORD.toCharArray()); } }