List of usage examples for java.security KeyStore setCertificateEntry
public final void setCertificateEntry(String alias, Certificate cert) throws KeyStoreException
From source file:com.liferay.sync.engine.lan.session.LanSession.java
private static SSLConnectionSocketFactory _getSSLSocketFactory() throws Exception { KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null);//www . j a v a 2 s. c o m for (SyncAccount syncAccount : SyncAccountService.findAll()) { if (!syncAccount.isActive() || !syncAccount.isLanEnabled()) { continue; } try { PrivateKey privateKey = LanPEMParserUtil.parsePrivateKey(syncAccount.getLanKey()); if (privateKey == null) { _logger.error("SyncAccount {} missing valid private key", syncAccount.getSyncAccountId()); continue; } X509Certificate x509Certificate = LanPEMParserUtil .parseX509Certificate(syncAccount.getLanCertificate()); if (x509Certificate == null) { _logger.error("SyncAccount {} missing valid certificate", syncAccount.getSyncAccountId()); continue; } keyStore.setCertificateEntry(syncAccount.getLanServerUuid(), x509Certificate); keyStore.setKeyEntry(syncAccount.getLanServerUuid(), privateKey, "".toCharArray(), new Certificate[] { x509Certificate }); } catch (Exception e) { _logger.error(e.getMessage(), e); } } KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, "".toCharArray()); TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); return new SNISSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier()); }
From source file:com.appdynamics.monitors.mongo.MongoDBMonitor.java
private SSLSocketFactory getSocketFactoryFromPEM(String filePath) throws Exception { Security.addProvider(new BouncyCastleProvider()); PEMParser pemParser = new PEMParser(new FileReader(getConfigFilename(filePath))); pemParser.readObject();/*from w w w . jav a 2 s . com*/ PemObject pemObject = pemParser.readPemObject(); pemParser.close(); X509CertificateHolder holder = new X509CertificateHolder(pemObject.getContent()); X509Certificate bc = new JcaX509CertificateConverter().setProvider("BC").getCertificate(holder); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null); keyStore.setCertificateEntry("ca", bc); TrustManager trustManager = TrustManagerUtils.getDefaultTrustManager(keyStore); SSLContext sslContext = SSLContextUtils.createSSLContext("TLS", null, trustManager); return sslContext.getSocketFactory(); }
From source file:com.gamesalutes.utils.EncryptUtils.java
/** * Creates an <code>SSLContext</code> that uses the specified trusted certificates. * // w w w . java2 s . co m * @param protocol the {@link TransportSecurityProtocol} to use for the context * @param trustedCerts certificates to import into the <code>SSLContext</code> or <code>null</code> * to accept all issuers * @param privateKey the client key to authenticate the client with the server * @return the created <code>SSLContext</code> * @throws Exception if error occurs during the process of creating the context */ public static SSLContext createSSLContext(TransportSecurityProtocol protocol, PrivateKey privateKey, java.security.cert.X509Certificate... trustedCerts) throws Exception { if (trustedCerts != null && trustedCerts.length == 0) throw new IllegalArgumentException("trustedCerts is empty"); X509TrustManager defaultManager = null; KeyManager[] keyManagers = null; KeyStore keyStore = null; if (privateKey != null || trustedCerts != null) { // create a new key store instance that will install the certificates // and/or the private keys keyStore = KeyStore.getInstance(JKS_TYPE); keyStore.load(null, null); } // import the certs if (trustedCerts != null) { // set up the key manager for the certificates javax.net.ssl.TrustManagerFactory trustFact = javax.net.ssl.TrustManagerFactory .getInstance(KEY_MANAGEMENT_ALG_SUN_X509); // install the certificates in the key store and give them a unique alias int imported = 0; for (java.security.cert.X509Certificate cert : trustedCerts) { if (cert != null) keyStore.setCertificateEntry("cert" + ++imported, cert); } if (imported == 0) throw new IllegalArgumentException("no non-null certs in trustedCerts"); // add the certs to the trust factory trustFact.init(keyStore); // get a default trust manager TrustManager[] tms = trustFact.getTrustManagers(); if (tms != null && tms.length >= 1) defaultManager = (X509TrustManager) tms[0]; } // import the private key if (privateKey != null) { keyStore.setKeyEntry("client", privateKey, null, null); KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(privateKey.getAlgorithm()); kmfactory.init(keyStore, null); keyManagers = kmfactory.getKeyManagers(); } //create the SSL context based on these parameters SSLContext sslContext = SSLContext.getInstance(protocol.toString()); // use a CertX509TrustManager since default one will still fail validation for // self-signed certs sslContext.init(keyManagers, new TrustManager[] { trustedCerts != null ? new CertX509TrustManager(defaultManager, trustedCerts) : new CertX509TrustManager() }, null); return sslContext; }
From source file:com.mytalentfolio.h_daforum.CconnectToServer.java
/** * Creates a new instance of KeyStore from provided certificate. * /*from w w w . j av a2 s.c o m*/ * @param ca * the certificate to get KeyStore * @return the new {@code KeyStore} instance. * @throws KeyStoreException * if an error occurred during the creation of the new KeyStore. * @throws NoSuchAlgorithmException * if the required algorithm is not available. * @throws CertificateException * if the specified certificate type is not available at any * installed provider. * @throws IOException * if an error occurs while closing this stream */ private KeyStore getKeyStore(Certificate ca) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("ca", ca); return keyStore; }
From source file:org.authme.android.util.AuthMeHttpClient.java
private SSLSocketFactory newSslSocketFactory() { try {// ww w . j a v a 2 s. c o m // Get an instance of the Bouncy Castle KeyStore format KeyStore trusted = KeyStore.getInstance("BKS"); // Could probably load the main keystore and then append, but this works trusted.load(null, null); InputStream is = context.getResources().openRawResource(R.raw.cacert_root); CertificateFactory certificateFactory = CertificateFactory.getInstance("X509"); Certificate certificate = certificateFactory.generateCertificate(is); trusted.setCertificateEntry("CACertRoot", certificate); // Now continue on using this keystore SSLSocketFactory sf = new SSLSocketFactory(trusted); // Hostname verification from certificate // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506 sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); return sf; } catch (Exception e) { throw new AssertionError(e); } }
From source file:org.apache.directory.studio.connection.core.StudioKeyStoreManager.java
private void addToKeyStore(X509Certificate certificate, KeyStore keyStore) throws Exception { // The alias is not relevant, it just needs to be an unique identifier. // The SHA-1 hash of the certificate should be unique. byte[] encoded = certificate.getEncoded(); String shaHex = DigestUtils.shaHex(encoded); keyStore.setCertificateEntry(shaHex, certificate); }
From source file:br.gov.serpro.cert.AuthSSLProtocolSocketFactory.java
private static KeyStore createKeyStore(final URL[] urls, final String[] passwords) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); keystore.load(null);/*from w w w .j a v a 2 s.c o m*/ if (urls == null) { throw new IllegalArgumentException("Keystore urls may not be null"); } if (passwords != null && passwords.length != urls.length) { throw new IllegalArgumentException("Urls and passwords arrays must have the same size"); } LOG.debug("Initializing key store"); for (int i = 0; i < urls.length; i++) { LOG.debug("Adding " + urls[i].toString() + " to internal keystore"); KeyStore ks = KeyStore.getInstance("jks"); InputStream is = null; try { is = urls[i].openStream(); if (passwords == null) { ks.load(is, null); } else { ks.load(is, passwords[i] != null ? passwords[i].toCharArray() : null); } for (Enumeration<String> e = ks.aliases(); e.hasMoreElements();) { X509Certificate cert = (X509Certificate) ks.getCertificate(e.nextElement()); keystore.setCertificateEntry(cert.getSubjectX500Principal().getName(), cert); } } catch (IOException e) { if (AuthSSLProtocolSocketFactory.setup.getParameter("debug").equalsIgnoreCase("true")) { System.out.println("Erro ao abrir URL: " + urls[i].toExternalForm()); } } finally { if (is != null) is.close(); } } return keystore; }
From source file:org.opendaylight.aaa.cert.impl.ODLKeyTool.java
public boolean addCertificate(final String keyStoreName, final String keyStorePwd, final String certificate, final String alias) { try {/* w ww . ja va 2s . c om*/ final X509Certificate newCert = getCertificate(certificate); final KeyStore keyStore = KeyStore.getInstance("JKS"); final FileInputStream fInputStream = new FileInputStream(workingDir + keyStoreName); keyStore.load(fInputStream, keyStorePwd.toCharArray()); if (keyStore.isCertificateEntry(alias)) { keyStore.deleteEntry(alias); } keyStore.setCertificateEntry(alias, newCert); keyStore.store(new FileOutputStream(workingDir + keyStoreName), keyStorePwd.toCharArray()); LOG.info("Certificate {} Added to keyStore {}", alias, keyStoreName); return true; } catch (CertificateException | KeyStoreException | NoSuchAlgorithmException | IOException e) { LOG.error("failed to add certificate", e); return false; } }
From source file:org.opendaylight.aaa.cert.impl.ODLMdsalKeyTool.java
public KeyStore createTrustKeyStoreImportCert(final String keyStorePwd, final List<Certificates> certificates) { try {/*from w ww .j a v a2 s . c o m*/ final KeyStore trustKeyStore = KeyStore.getInstance("JKS"); trustKeyStore.load(null, keyStorePwd.toCharArray()); for (final Certificates certificate : certificates) { final X509Certificate newCert = getCertificate(certificate.getX500Certificate()); if (newCert != null) { trustKeyStore.setCertificateEntry(certificate.getAlias(), newCert); } } LOG.info("trust keystore is created"); return trustKeyStore; } catch (final KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) { LOG.error("Failed to create trust keystore", e); return null; } }
From source file:org.guanxi.sp.engine.security.GuardVerifier.java
/** * Blocks Guard access to a service until the Guard can be verified. * * @param request Standard HttpServletRequest * @param response Standard HttpServletResponse * @param object handler/*from w w w . j a va2s . com*/ * @return true if the caller is authorised to use the service * @throws Exception if an error occurs */ public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception { String guardID = request.getParameter(Guanxi.WAYF_PARAM_GUARD_ID); String sessionID = request.getParameter(Guanxi.WAYF_PARAM_SESSION_ID); if ((guardID == null) || (sessionID == null)) { logger.error("Cant' verify Guard due to missing parameter"); request.setAttribute("error", messages.getMessage("engine.error.missing.guard.verification.parameter", null, request.getLocale())); request.setAttribute("message", messages.getMessage("engine.error.missing.guard.verification.parameter", null, request.getLocale())); request.getRequestDispatcher(errorPage).forward(request, response); return false; } EntityDescriptorType guardEntityDescriptor = (EntityDescriptorType) servletContext.getAttribute(guardID); if (guardEntityDescriptor == null) { logger.error("Guard '" + guardID + "' not found in metadata repository"); request.setAttribute("error", messages.getMessage("engine.error.no.guard.metadata", null, request.getLocale())); request.setAttribute("message", messages.getMessage("engine.error.no.guard.metadata", null, request.getLocale())); request.getRequestDispatcher(errorPage).forward(request, response); return false; } Config config = (Config) servletContext.getAttribute(Guanxi.CONTEXT_ATTR_ENGINE_CONFIG); if (config == null) { logger.error("Guard '" + guardID + "' wants to talk but Engine hasn't finished initialisation"); request.setAttribute("error", messages.getMessage("engine.error.not.initialised", null, request.getLocale())); request.setAttribute("message", messages.getMessage("engine.error.not.initialised", null, request.getLocale())); request.getRequestDispatcher(errorPage).forward(request, response); return false; } // Load the GuanxiGuardService node from the metadata GuardRoleDescriptorExtensions guardNativeMetadata = Util.getGuardNativeMetadata(guardEntityDescriptor); // Build the REST URL to verify the Guard's session String queryString = guardNativeMetadata.getVerifierURL() + "?" + Guanxi.SESSION_VERIFIER_PARAM_SESSION_ID + "=" + sessionID; // If we haven't already checked the Guard for secure comms, do it now if (servletContext.getAttribute(guardID + "SECURE_CHECK_DONE_SP") == null) { // Load up the Guard's native metadata... GuardRoleDescriptorExtensions guardExt = Util.getGuardNativeMetadata(guardEntityDescriptor); // ...and see if it's using HTTPS try { if (Util.isGuardSecure(guardExt)) { logger.info("Probing for Guard certificate for : " + guardID); /* If the Guard is using HTTPS then we'll need to connect to it, extract it's * certificate and add it to our truststore. To do that, we'll need to use our * own keystore to let the Guard authenticate us. */ EntityConnection guardConnection = new EntityConnection(queryString, config.getCertificateAlias(), // alias of cert config.getKeystore(), config.getKeystorePassword(), config.getTrustStore(), config.getTrustStorePassword(), EntityConnection.PROBING_ON); X509Certificate guardX509 = guardConnection.getServerCertificate(); // We've got the Guard's X509 so add it to our truststore... KeyStore engineTrustStore = KeyStore.getInstance("jks"); engineTrustStore.load(new FileInputStream(config.getTrustStore()), config.getTrustStorePassword().toCharArray()); // ...under it's Subject DN as an alias... engineTrustStore.setCertificateEntry(guardID, guardX509); // ...and rewrite the trust store engineTrustStore.store(new FileOutputStream(config.getTrustStore()), config.getTrustStorePassword().toCharArray()); // Mark Guard as having been checked for secure comms servletContext.setAttribute(guardID + "SECURE_CHECK_DONE_SP", "SECURE"); logger.info("Added : " + guardID + " to truststore"); } else { // Mark Guard as having been checked for secure comms servletContext.setAttribute(guardID + "SECURE_CHECK_DONE_SP", "NOT_SECURE"); } } catch (Exception e) { logger.error("Failed to probe Guard : " + guardID + " for cert : ", e); request.setAttribute("error", messages.getMessage("engine.error.guard.comms.failed", null, request.getLocale())); request.setAttribute("message", messages.getMessage("engine.error.guard.comms.failed", null, request.getLocale())); request.getRequestDispatcher(errorPage).forward(request, response); return false; } } // Verify that the Guard actually sent the request String verificationResult = null; try { EntityConnection verifierService = new EntityConnection(queryString, config.getCertificateAlias(), // alias of cert config.getKeystore(), config.getKeystorePassword(), config.getTrustStore(), config.getTrustStorePassword(), EntityConnection.PROBING_OFF); verifierService.setDoOutput(true); verifierService.connect(); verificationResult = verifierService.getContentAsString(); } catch (GuanxiException ge) { logger.error("Guard '" + guardID + "' error during verification : ", ge); request.setAttribute("error", messages.getMessage("engine.error.guard.comms.failed", null, request.getLocale())); request.setAttribute("message", messages.getMessage("engine.error.guard.comms.failed", null, request.getLocale())); request.getRequestDispatcher(errorPage).forward(request, response); return false; } // Did the Guard verify the session? if (!verificationResult.equals(Guanxi.SESSION_VERIFIER_RETURN_VERIFIED)) { logger.error("Guard '" + guardID + "' error during verification : " + verificationResult); request.setAttribute("error", messages.getMessage("engine.error.guard.failed.verification", null, request.getLocale())); request.setAttribute("message", messages.getMessage("engine.error.guard.failed.verification", null, request.getLocale())); request.getRequestDispatcher(errorPage).forward(request, response); return false; } /* Convert the Guard's session ID to an Engine session ID and store the Guard's GuanxiGuardService * node under it. */ servletContext.setAttribute(sessionID.replaceAll("GUARD", "ENGINE"), guardEntityDescriptor); return true; }