List of usage examples for java.security KeyStore setCertificateEntry
public final void setCertificateEntry(String alias, Certificate cert) throws KeyStoreException
From source file:com.vmware.bdd.manager.SoftwareManagerCollector.java
/** * TODO this method has to be reverted:// www. j a v a2 s .co m * because if the target path is not accessible, it will load cert from the default keystore in java home, * but still try to write it to the non accessible path. * @param certificate * @param keyStorePath */ protected static void saveSslCertificate(String certificate, String keyStorePath) { Certificate[] certs; //parse certificates try { if (CommonUtil.isBlank(certificate)) { throw SoftwareManagerCollectorException.BAD_CERT(null); } byte[] certBytes = Base64.decodeBase64(certificate.replaceAll("-----BEGIN CERTIFICATE-----", "") .replaceAll("-----END CERTIFICATE-----", "").getBytes()); CertificateFactory cf = CertificateFactory.getInstance("X.509"); Collection c = cf.generateCertificates(new ByteArrayInputStream(certBytes)); certs = new Certificate[c.toArray().length]; if (c.size() == 0) { throw SoftwareManagerCollectorException.BAD_CERT(null); } else if (c.size() == 1) { certs[0] = cf.generateCertificate(new ByteArrayInputStream(certBytes)); } else { certs = (Certificate[]) c.toArray(certs); } } catch (CertificateException e) { throw SoftwareManagerCollectorException.BAD_CERT(e); } //load & save keystore OutputStream out = null; try { KeyStore keyStore = CommonUtil.loadAppMgrKeyStore(keyStorePath); if (keyStore == null) { logger.error(Messages.getString("SW_MGR_COLLECTOR.CANNT_READ_KEYSTORE")); throw new SWMgrCollectorInternalException( Messages.getString("SW_MGR_COLLECTOR.CANNT_READ_KEYSTORE")); } MessageDigest md5 = MessageDigest.getInstance("MD5"); String md5Fingerprint = ""; for (Certificate cert : certs) { md5.update(cert.getEncoded()); md5Fingerprint = CommonUtil.toHexString(md5.digest()); logger.debug("md5 finger print: " + md5Fingerprint); logger.debug("added cert: " + cert); keyStore.setCertificateEntry(md5Fingerprint, cert); } out = new FileOutputStream(keyStorePath + Constants.APPMANAGER_KEYSTORE_FILE); keyStore.store(new BufferedOutputStream(out), Constants.APPMANAGER_KEYSTORE_PASSWORD); } catch (CertificateException | NoSuchAlgorithmException | IOException | KeyStoreException e) { logger.error(Messages.getString("SW_MGR_COLLECTOR.FAIL_SAVE_CERT"), e); throw new SWMgrCollectorInternalException(e, Messages.getString("SW_MGR_COLLECTOR.FAIL_SAVE_CERT")); } finally { if (out != null) { try { out.close(); } catch (IOException e) { logger.warn("Output stream of appmanagers.jks close failed."); } } } }
From source file:com.amazon.alexa.avs.auth.companionservice.CompanionServiceClient.java
/** * Loads the CA certificate into an in-memory keystore and creates an {@link SSLSocketFactory}. * * @return SSLSocketFactory//from w w w . j a va 2s. co m */ public SSLSocketFactory getPinnedSSLSocketFactory() { InputStream caCertInputStream = null; InputStream clientKeyPair = null; try { // Load the CA certificate into memory CertificateFactory cf = CertificateFactory.getInstance("X.509"); caCertInputStream = new FileInputStream(deviceConfig.getCompanionServiceInfo().getSslCaCert()); Certificate caCert = cf.generateCertificate(caCertInputStream); // Load the CA certificate into the trusted KeyStore KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); trustStore.setCertificateEntry("myca", caCert); // Create a TrustManagerFactory with the trusted KeyStore TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(trustStore); // Load the client certificate and private key into another KeyStore KeyStore keyStore = KeyStore.getInstance("PKCS12"); clientKeyPair = new FileInputStream(deviceConfig.getCompanionServiceInfo().getSslClientKeyStore()); keyStore.load(clientKeyPair, deviceConfig.getCompanionServiceInfo().getSslClientKeyStorePassphrase().toCharArray()); // Create a TrustManagerFactory with the client key pair KeyStore KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, deviceConfig.getCompanionServiceInfo().getSslClientKeyStorePassphrase().toCharArray()); // Initialize the SSLContext and return an SSLSocketFactory; SSLContext sc = SSLContext.getInstance("TLS"); sc.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); return sc.getSocketFactory(); } catch (CertificateException | KeyStoreException | UnrecoverableKeyException | NoSuchAlgorithmException | IOException | KeyManagementException e) { throw new RuntimeException("The KeyStore for contacting the Companion Service could not be loaded.", e); } finally { IOUtils.closeQuietly(caCertInputStream); IOUtils.closeQuietly(clientKeyPair); } }
From source file:org.apache.accumulo.test.util.CertUtils.java
public void createPublicCert(File targetKeystoreFile, String keyName, String rootKeystorePath, String rootKeystorePassword, String truststorePassword) throws NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException, KeyStoreException, UnrecoverableKeyException { KeyStore signerKeystore = KeyStore.getInstance(keystoreType); char[] signerPasswordArray = rootKeystorePassword.toCharArray(); try (FileInputStream fis = new FileInputStream(rootKeystorePath)) { signerKeystore.load(fis, signerPasswordArray); }/*from w w w .j a va 2s . c om*/ Certificate rootCert = findCert(signerKeystore); KeyStore keystore = KeyStore.getInstance(keystoreType); keystore.load(null, null); keystore.setCertificateEntry(keyName + "Cert", rootCert); try (FileOutputStream fos = new FileOutputStream(targetKeystoreFile)) { keystore.store(fos, truststorePassword.toCharArray()); } }
From source file:org.apache.accumulo.test.util.CertUtils.java
public void createSelfSignedCert(File targetKeystoreFile, String keyName, String keystorePassword) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException, OperatorCreationException, AccumuloSecurityException, NoSuchProviderException { if (targetKeystoreFile.exists()) { throw new FileExistsException(targetKeystoreFile); }/*from w w w .j a va2 s. com*/ KeyPair kp = generateKeyPair(); X509CertificateObject cert = generateCert(keyName, kp, true, kp.getPublic(), kp.getPrivate()); char[] password = keystorePassword.toCharArray(); KeyStore keystore = KeyStore.getInstance(keystoreType); keystore.load(null, null); keystore.setCertificateEntry(keyName + "Cert", cert); keystore.setKeyEntry(keyName + "Key", kp.getPrivate(), password, new Certificate[] { cert }); try (FileOutputStream fos = new FileOutputStream(targetKeystoreFile)) { keystore.store(fos, password); } }
From source file:org.apache.accumulo.test.util.CertUtils.java
public void createSignedCert(File targetKeystoreFile, String keyName, String keystorePassword, String signerKeystorePath, String signerKeystorePassword) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException, OperatorCreationException, AccumuloSecurityException, UnrecoverableKeyException, NoSuchProviderException { KeyStore signerKeystore = KeyStore.getInstance(keystoreType); char[] signerPasswordArray = signerKeystorePassword.toCharArray(); try (FileInputStream fis = new FileInputStream(signerKeystorePath)) { signerKeystore.load(fis, signerPasswordArray); }//from w w w . j a va 2 s. c o m Certificate signerCert = findCert(signerKeystore); PrivateKey signerKey = findPrivateKey(signerKeystore, signerPasswordArray); KeyPair kp = generateKeyPair(); X509CertificateObject cert = generateCert(keyName, kp, false, signerCert.getPublicKey(), signerKey); char[] password = keystorePassword.toCharArray(); KeyStore keystore = KeyStore.getInstance(keystoreType); keystore.load(null, null); keystore.setCertificateEntry(keyName + "Cert", cert); keystore.setKeyEntry(keyName + "Key", kp.getPrivate(), password, new Certificate[] { cert, signerCert }); try (FileOutputStream fos = new FileOutputStream(targetKeystoreFile)) { keystore.store(fos, password); } }
From source file:org.gvnix.service.roo.addon.addon.security.GvNix509TrustManager.java
/** * Import certs in this.chain to the keystore given by the file passed. * //from w w w.j av a 2s . c om * @param host * @param keystore * @param pass * @return * @throws Exception */ public X509Certificate[] addCerts(String host, File keystore, char[] pass) throws Exception { // Specific Exceptions thrown in this code: NoSuchAlgorithmException, // KeyStoreException, CertificateException, IOException X509Certificate[] chain = this.chain; if (chain == null) { return null; } KeyStore ks = loadKeyStore(keystore, pass); String alias = host; for (int i = 0; i < chain.length; i++) { X509Certificate cert = chain[i]; alias = alias.concat("-" + (i + 1)); ks.setCertificateEntry(alias, cert); alias = host; } if (keystore.canWrite()) { OutputStream out = null; try { out = new FileOutputStream(keystore); ks.store(out, pass); } finally { IOUtils.closeQuietly(out); } } else { throw new Exception(keystore.getAbsolutePath().concat(" is not writable. ") .concat("You should to import needed certificates in your") .concat(" JVM trustcacerts keystore.\n").concat("You have them in src/main/resources/*.cer.\n") .concat("Use keytool for that: ") .concat("http://download.oracle.com/javase/6/docs/technotes/tools/solaris/keytool.html")); } return chain; }
From source file:eu.musesproject.client.connectionmanager.TLSManager.java
/** * Convert local certificate to BKS/*from w w w. j ava 2s. c o m*/ * @param cerStream * @param alias * * @param password * @return keyStore */ private KeyStore convertCerToBKS(InputStream cerStream, String alias, char[] password) { KeyStore keyStore = null; try { keyStore = KeyStore.getInstance("BKS", "BC"); CertificateFactory factory = CertificateFactory.getInstance("X.509", "BC"); Certificate certificate = factory.generateCertificate(cerStream); keyStore.load(null, password); keyStore.setCertificateEntry(alias, certificate); } catch (Exception e) { Log.d(TAG, e.getLocalizedMessage()); } return keyStore; }
From source file:org.disrupted.rumble.database.statistics.StatisticManager.java
public void onEventAsync(LinkLayerStarted event) { if (!event.linkLayerIdentifier.equals(WifiLinkLayerAdapter.LinkLayerIdentifier)) return;/*from ww w.j a va 2 s .co m*/ if (RumblePreferences.UserOkWithSharingAnonymousData(RumbleApplication.getContext()) && RumblePreferences.isTimeToSync(RumbleApplication.getContext())) { if (!NetUtil.isURLReachable("http://disruptedsystems.org/")) return; try { // generate the JSON file byte[] json = generateStatJSON().toString().getBytes(); // configure SSL CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream caInput = new BufferedInputStream( RumbleApplication.getContext().getAssets().open("certs/disruptedsystemsCA.pem")); Certificate ca = cf.generateCertificate(caInput); String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("ca", ca); String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, tmf.getTrustManagers(), null); URL url = new URL("https://data.disruptedsystems.org/post"); HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection(); urlConnection.setSSLSocketFactory(sslContext.getSocketFactory()); // then configure the header urlConnection.setInstanceFollowRedirects(true); urlConnection.setRequestMethod("POST"); urlConnection.setDoOutput(true); urlConnection.setRequestProperty("Content-Type", "application/json"); urlConnection.setRequestProperty("Accept", "application/json"); urlConnection.setRequestProperty("charset", "utf-8"); urlConnection.setRequestProperty("Content-Length", Integer.toString(json.length)); urlConnection.setUseCaches(false); // connect and send the JSON urlConnection.setConnectTimeout(10 * 1000); urlConnection.connect(); urlConnection.getOutputStream().write(json); if (urlConnection.getResponseCode() != 200) throw new IOException("request failed"); // erase the database RumblePreferences.updateLastSync(RumbleApplication.getContext()); cleanDatabase(); } catch (Exception ex) { Log.e(TAG, "Failed to establish SSL connection to server: " + ex.toString()); } } }
From source file:org.jboss.as.test.integration.security.common.CoreUtils.java
private static void createKeyStoreTrustStore(KeyStore keyStore, KeyStore trustStore, String DN, String alias) throws Exception { X500Principal principal = new X500Principal(DN); SelfSignedX509CertificateAndSigningKey selfSignedX509CertificateAndSigningKey = SelfSignedX509CertificateAndSigningKey .builder().setKeyAlgorithmName("RSA").setSignatureAlgorithmName("SHA256withRSA").setDn(principal) .setKeySize(1024).build();/*from w w w . ja v a 2 s .c o m*/ X509Certificate certificate = selfSignedX509CertificateAndSigningKey.getSelfSignedCertificate(); keyStore.setKeyEntry(alias, selfSignedX509CertificateAndSigningKey.getSigningKey(), KEYSTORE_CREATION_PASSWORD, new X509Certificate[] { certificate }); if (trustStore != null) trustStore.setCertificateEntry(alias, certificate); }
From source file:org.soyatec.windowsazure.internal.util.ssl.SslUtil.java
/** * Return the file's absolute path name string * /*w w w . j a va2 s . co m*/ * @param x509Cert * @return Path name string * @throws Exception */ public static String importCertificate(String x509Cert) throws Exception { // CREATE A KEYSTORE OF TYPE "Java Key Store" KeyStore ks = KeyStore.getInstance("JKS"); /* * LOAD THE STORE The first time you're doing this (i.e. the keystore * does not yet exist - you're creating it), you HAVE to load the * keystore from a null source with null password. Before any methods * can be called on your keystore you HAVE to load it first. Loading it * from a null source and null password simply creates an empty * keystore. At a later time, when you want to verify the keystore or * get certificates (or whatever) you can load it from the file with * your password. */ ks.load(null, null); // GET THE FILE CONTAINING YOUR CERTIFICATE File x509 = new File(x509Cert); FileInputStream fis = new FileInputStream(x509); BufferedInputStream bis = new BufferedInputStream(fis); // I USE x.509 BECAUSE THAT'S WHAT keytool CREATES CertificateFactory cf = CertificateFactory.getInstance("X.509"); // NOTE: THIS IS java.security.cert.Certificate NOT // java.security.Certificate X509Certificate cert = (X509Certificate) cf.generateCertificate(bis); ks.setCertificateEntry(CERT_ALIAS, cert); // SAVE THE KEYSTORE TO A FILE /* * After this is saved, I believe you can just do setCertificateEntry to * add entries and then not call store. I believe it will update the * existing store you load it from and not just in memory. */ File storeFile = new File(x509.getParentFile().getAbsolutePath(), KEYSTORE); ks.store(new FileOutputStream(storeFile), KEYSTORE_PASS.toCharArray()); return storeFile.getAbsolutePath(); }