List of usage examples for java.security KeyStore setCertificateEntry
public final void setCertificateEntry(String alias, Certificate cert) throws KeyStoreException
From source file:com.esri.geoevent.datastore.GeoEventDataStoreProxy.java
private HttpClientConnectionManager createConnectionManager() throws GeneralSecurityException, IOException { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null);// w w w . j a v a2 s . c o m if (registry == null) { TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init((KeyStore) null); X509TrustManager x509TrustManager = null; for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) { if (trustManager instanceof X509TrustManager) { x509TrustManager = (X509TrustManager) trustManager; break; } } X509Certificate[] acceptedIssuers = x509TrustManager.getAcceptedIssuers(); if (acceptedIssuers != null) { // If this is null, something is really wrong... int issuerNum = 1; for (X509Certificate cert : acceptedIssuers) { trustStore.setCertificateEntry("issuer" + issuerNum, cert); issuerNum++; } } else { LOG.log(Level.INFO, "Didn't find any new certificates to trust."); } SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); sslContextBuilder.loadTrustMaterial(trustStore, new KnownArcGISCertificatesTrustStrategy(new ArrayList<>(trustedCerts))); SSLContext sslContext = sslContextBuilder.build(); SSLContext.setDefault(sslContext); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, new DataStoreProxyHostnameVerifier(new ArrayList<>(trustedCerts))); this.registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", sslSocketFactory).build(); } return new PoolingHttpClientConnectionManager(registry); }
From source file:com.corebase.android.framework.http.client.AsyncHttpClient.java
/** * ?SSLSocketFactory?https?/*w w w. ja va 2 s . c o m*/ * * @return * @throws KeyStoreException * @throws NoSuchAlgorithmException * @throws UnrecoverableKeyException * @throws KeyManagementException */ private CustomSSLSocketFactory initCustomSSLSocketFactory() throws KeyStoreException, KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException { KeyStore keyStore = null; try { InputStream ins = context.getAssets().open("app_pay.cer"); // ?assets if (ins != null) { CertificateFactory cerFactory = CertificateFactory.getInstance("X.509"); Certificate cer = cerFactory.generateCertificate(ins); keyStore = KeyStore.getInstance("PKCS12", "BC"); keyStore.load(null, null); keyStore.setCertificateEntry("trust", cer); } else { keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null); } CustomSSLSocketFactory customSSLSocketFactory = new CustomSSLSocketFactory(keyStore); customSSLSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); return customSSLSocketFactory; } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils.java
/** * This method generates a certificate from a base64 encoded certificate string and add to the configured trust * store./*from w w w. java 2s .c o m*/ * * @param base64Cert : The base 64 encoded string of the server certificate. * @param alias : The alias for the certificate. * @return : ResponseCode which matches the execution result. * * Response Codes. * SUCCESS : If certificate added successfully. * INTERNAL_SERVER_ERROR : If any internal error occurred * ALIAS_EXISTS_IN_TRUST_STORE : If the alias exists in trust store. * CERTIFICATE_EXPIRED : If the given certificate is expired. */ public ResponseCode addCertificateToTrustStore(String base64Cert, String alias) { boolean isCertExists = false; boolean expired = false; InputStream serverCert = null; try { //Decode base64 encoded certificate. byte[] cert = (Base64.decodeBase64(base64Cert.getBytes(CHARSET_UTF_8))); serverCert = new ByteArrayInputStream(cert); if (serverCert.available() == 0) { log.error("Certificate is empty for the provided alias " + alias); return ResponseCode.INTERNAL_SERVER_ERROR; } //Read the client-truststore.jks into a KeyStore. File trustStoreFile = new File(TRUST_STORE); localTrustStoreStream = new FileInputStream(trustStoreFile); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(localTrustStoreStream, TRUST_STORE_PASSWORD); CertificateFactory cf = CertificateFactory.getInstance(CERTIFICATE_TYPE); while (serverCert.available() > 0) { Certificate certificate = cf.generateCertificate(serverCert); //Check whether the Alias exists in the trust store. if (trustStore.containsAlias(alias)) { isCertExists = true; } else { /* * If alias is not exists, check whether the certificate is expired or not. If expired set the * expired flag. * */ X509Certificate x509Certificate = (X509Certificate) certificate; if (x509Certificate.getNotAfter().getTime() <= System.currentTimeMillis()) { expired = true; if (log.isDebugEnabled()) { log.debug("Provided certificate is expired."); } } else { //If not expired add the certificate to trust store. trustStore.setCertificateEntry(alias, certificate); } } } fileOutputStream = new FileOutputStream(trustStoreFile); trustStore.store(fileOutputStream, TRUST_STORE_PASSWORD); responseCode = expired ? ResponseCode.CERTIFICATE_EXPIRED : isCertExists ? ResponseCode.ALIAS_EXISTS_IN_TRUST_STORE : ResponseCode.SUCCESS; } catch (CertificateException e) { log.error("Error loading certificate.", e); responseCode = ResponseCode.INTERNAL_SERVER_ERROR; } catch (FileNotFoundException e) { log.error("Error reading/ writing to the certificate file.", e); responseCode = ResponseCode.INTERNAL_SERVER_ERROR; } catch (NoSuchAlgorithmException e) { log.error("Could not find the algorithm to load the certificate.", e); responseCode = ResponseCode.INTERNAL_SERVER_ERROR; } catch (UnsupportedEncodingException e) { log.error("Error retrieving certificate from String", e); responseCode = ResponseCode.INTERNAL_SERVER_ERROR; } catch (KeyStoreException e) { log.error("Error reading certificate contents.", e); responseCode = ResponseCode.INTERNAL_SERVER_ERROR; } catch (IOException e) { log.error("Error in loading the certificate.", e); responseCode = ResponseCode.INTERNAL_SERVER_ERROR; } finally { closeStreams(localTrustStoreStream, fileOutputStream, serverCert); } return responseCode; }
From source file:org.sufficientlysecure.keychain.ui.SettingsSmartPGPAuthorityFragment.java
private boolean editAuthority(final String old_alias, final String new_alias, final int position, final String uri) { try {//from w ww . j a va2 s . co m final KeyStore ks = SettingsSmartPGPAuthoritiesActivity.readKeystore(getContext()); if (ks == null) { throw new KeyStoreException("no keystore found"); } Certificate old_cert = null; if (old_alias != null) { old_cert = ks.getCertificate(old_alias); ks.deleteEntry(old_alias); mAuthorities.remove(old_alias); mAdapter.notifyItemRemoved(position); } Certificate new_cert = null; if (uri == null) { new_cert = old_cert; } else { final InputStream fis = getContext().getContentResolver().openInputStream(Uri.parse(uri)); final CertificateFactory cf = CertificateFactory.getInstance("X.509"); new_cert = cf.generateCertificate(fis); if (!(new_cert instanceof X509Certificate)) { Notify.create(getActivity(), "Invalid certificate", Notify.LENGTH_LONG, Notify.Style.ERROR) .show(); return false; } fis.close(); } if (new_alias == null || new_cert == null) { Notify.create(getActivity(), "Missing alias or certificate", Notify.LENGTH_LONG, Notify.Style.ERROR) .show(); return false; } final X509Certificate x509cert = (X509Certificate) new_cert; x509cert.checkValidity(); ks.setCertificateEntry(new_alias, x509cert); SettingsSmartPGPAuthoritiesActivity.writeKeystore(getContext(), ks); mAuthorities.add(new_alias); mAdapter.notifyItemInserted(mAuthorities.size() - 1); return true; } catch (IOException e) { Notify.create(getActivity(), "failed to open certificate (" + e.getMessage() + ")", Notify.LENGTH_LONG, Notify.Style.ERROR).show(); } catch (CertificateException e) { Notify.create(getActivity(), "invalid certificate (" + e.getMessage() + ")", Notify.LENGTH_LONG, Notify.Style.ERROR).show(); } catch (KeyStoreException e) { Notify.create(getActivity(), "invalid keystore (" + e.getMessage() + ")", Notify.LENGTH_LONG, Notify.Style.ERROR).show(); } return false; }
From source file:org.oscarehr.sharingcenter.actions.SecurityInfrastructureServlet.java
private String importCertificates(Integer infrastructureId, InputStream inputStream) { String status = "fail"; OscarProperties oscarProperties = OscarProperties.getInstance(); String keyStoreFile = oscarProperties.getProperty("TOMCAT_KEYSTORE_FILE"); String trustStoreFile = oscarProperties.getProperty("TOMCAT_TRUSTSTORE_FILE"); String keyStorePass = oscarProperties.getProperty("TOMCAT_KEYSTORE_PASSWORD"); String trustStorePass = oscarProperties.getProperty("TOMCAT_TRUSTSTORE_PASSWORD"); InfrastructureDao dao = SpringUtils.getBean(InfrastructureDao.class); InfrastructureDataObject infrastructure = dao.getInfrastructure(infrastructureId); String alias = infrastructure.getAlias(); PrivateKey privateKey = null; KeyStore ks = null;/*from w w w .j a va 2 s. c o m*/ KeyStore ts = null; try { //acquiring the private key Base64 base64 = new Base64(); byte[] privKey = base64.decode(infrastructure.getBase64EncodedPrivateKey()); privateKey = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(privKey)); ks = SslUtility.loadKeyStore(keyStoreFile, keyStorePass.toCharArray()); ts = SslUtility.loadKeyStore(trustStoreFile, trustStorePass.toCharArray()); } catch (SslException ex) { LOGGER.info(ex); } catch (InvalidKeySpecException ex) { LOGGER.info(ex); } catch (NoSuchAlgorithmException ex) { LOGGER.info(ex); } if (ks != null && ts != null && privateKey != null) { // import certificates to keystore and truststore try { // extract certificates ArrayList<X509Certificate> certificates = SslUtility.extractX509Certificates(inputStream); // get the private key and add certificate chain X509Certificate[] chain = new X509Certificate[2]; ks.setKeyEntry(alias, privateKey, keyStorePass.toCharArray(), certificates.toArray(chain)); // save the keystore ks.store(new FileOutputStream(keyStoreFile), keyStorePass.toCharArray()); // add root CA certificate truststore ArrayList<X509Certificate> caCerts = SslUtility.retrieveCACertificates(certificates); for (X509Certificate x509Certificate : caCerts) { ts.setCertificateEntry(alias, x509Certificate); } // save the truststore ts.store(new FileOutputStream(trustStoreFile), trustStorePass.toCharArray()); status = "import"; } catch (NoSuchAlgorithmException ex) { LOGGER.info(ex); } catch (CertificateException ex) { LOGGER.info(ex); } catch (KeyStoreException ex) { LOGGER.info(ex); } catch (IOException ex) { LOGGER.info(ex); } catch (SslException ex) { LOGGER.info(ex); } } else { LOGGER.debug("Bad data. Keystore/Truststore/PrivateKey might be null"); } return status; }
From source file:com.tremolosecurity.openunison.util.OpenUnisonUtils.java
private static void importMetaData(KeyStore ks, EntityDescriptor ed, IDPSSODescriptor idp, AuthMechType currentMechanism, HashMap<String, ParamType> params) throws Base64DecodingException, CertificateException, KeyStoreException { setProperty("entityID", ed.getEntityID(), params, currentMechanism); setProperty("entityID", ed.getEntityID(), params, currentMechanism); for (SingleSignOnService sso : idp.getSingleSignOnServices()) { if (sso.getBinding().equalsIgnoreCase("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST")) { setProperty("idpURL", sso.getLocation(), params, currentMechanism); } else if (sso.getBinding().equalsIgnoreCase("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect")) { setProperty("idpRedirURL", sso.getLocation(), params, currentMechanism); }//w ww. j a v a2s. c o m } for (SingleLogoutService slo : idp.getSingleLogoutServices()) { if (slo.getBinding().equalsIgnoreCase("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect")) { setProperty("idpRedirLogoutURL", slo.getLocation(), params, currentMechanism); } } for (KeyDescriptor kd : idp.getKeyDescriptors()) { if (kd.getUse().equals(UsageType.SIGNING)) { String base64 = kd.getKeyInfo().getX509Datas().get(0).getX509Certificates().get(0).getValue(); String name = "verify-" + ed.getEntityID() + "-idp-sig"; ByteArrayInputStream bais = new ByteArrayInputStream(Base64.decode(base64)); CertificateFactory cf = CertificateFactory.getInstance("X.509"); Collection<? extends Certificate> c = cf.generateCertificates(bais); if (c.size() > 1) { int j = 0; Iterator<? extends Certificate> i = c.iterator(); while (i.hasNext()) { Certificate certificate = (Certificate) i.next(); ks.setCertificateEntry(name + "-" + j, certificate); } } else { ks.setCertificateEntry(name, c.iterator().next()); } setProperty("idpSigKeyName", name, params, currentMechanism); } } }
From source file:org.tolven.config.model.CredentialManager.java
public void processTrustStore(TrustStoreDetail trustStoreDetail) { try {//from w w w .j av a2s.c o m Set<X509Certificate> newTrustStoreCerts = new HashSet<X509Certificate>(); Set<X509Certificate> previousTrustStoreCerts = new HashSet<X509Certificate>(); Set<X509Certificate> resultingTrustStoreCerts = new HashSet<X509Certificate>(); for (TrustStoreCertificateDetail trustStoreCertificateDetail : trustStoreDetail.getCertificate()) { CertificateGroupDetail certGroup = getTolvenConfigWrapper() .getCredentialGroup(trustStoreCertificateDetail.getRefId()); if (certGroup == null) { throw new RuntimeException("The trusted group " + trustStoreCertificateDetail.getRefId() + " in truststore " + trustStoreDetail.getId() + " does not exist"); } X509Certificate trustStoreX509Certificate = getTolvenConfigWrapper().getX509Certificate(certGroup); newTrustStoreCerts.add(trustStoreX509Certificate); } File trustStoreFile = new File(trustStoreDetail.getSource()); if (TolvenConfigWrapper.TOLVEN_CREDENTIAL_FORMAT_PEM.equals(trustStoreDetail.getFormat())) { if (trustStoreFile.exists()) { previousTrustStoreCerts = getTolvenConfigWrapper().getX509Certificates(trustStoreFile); for (X509Certificate cert : previousTrustStoreCerts) { resultingTrustStoreCerts.add(cert); } } // And now for what Java calls a Set intersection resultingTrustStoreCerts.retainAll(newTrustStoreCerts); if (resultingTrustStoreCerts.size() != newTrustStoreCerts.size() || !resultingTrustStoreCerts.containsAll(newTrustStoreCerts)) { FileOutputStream out = null; try { out = new FileOutputStream(trustStoreFile); for (X509Certificate x509Certificate : newTrustStoreCerts) { out.write(convertToPEMBytes(x509Certificate)); } } finally { if (out != null) { out.close(); } } logger.info("Created truststore: " + trustStoreDetail.getId()); } } else if (TolvenConfigWrapper.TOLVEN_CREDENTIAL_FORMAT_JKS.equals(trustStoreDetail.getFormat()) || TolvenConfigWrapper.TOLVEN_CREDENTIAL_FORMAT_PKCS12.equals(trustStoreDetail.getFormat())) { char[] truststorepass = getPasswordHolder().getPassword(trustStoreDetail.getId()); if (trustStoreFile.exists()) { KeyStore trustStore = getTolvenConfigWrapper().getKeyStore(truststorepass, trustStoreFile, trustStoreDetail.getFormat()); Enumeration<String> enumeration = trustStore.aliases(); while (enumeration.hasMoreElements()) { String alias = enumeration.nextElement(); X509Certificate cert = (X509Certificate) trustStore.getCertificate(alias); previousTrustStoreCerts.add(cert); resultingTrustStoreCerts.add(cert); } } // And now for what Java calls a Set intersection resultingTrustStoreCerts.retainAll(newTrustStoreCerts); if (resultingTrustStoreCerts.size() != newTrustStoreCerts.size() || !resultingTrustStoreCerts.containsAll(newTrustStoreCerts)) { KeyStore trustStore = KeyStore.getInstance(trustStoreDetail.getFormat()); trustStore.load(null, truststorepass); for (X509Certificate newCert : newTrustStoreCerts) { String alias = newCert.getSubjectDN().getName(); trustStore.setCertificateEntry(alias, newCert); } trustStoreFile.getParentFile().mkdirs(); write(trustStore, trustStoreFile, truststorepass); logger.info("Created truststore: " + trustStoreDetail.getId()); } } else { throw new RuntimeException("Unrecognized keystore format: " + trustStoreDetail.getFormat()); } } catch (Exception ex) { throw new RuntimeException("Failed to process truststore: " + trustStoreDetail.getId(), ex); } }
From source file:org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils.java
/** * Method to update the certificate which matches the given alias. * * @param certificate: The base64 encoded certificate string. * @param alias : Alias of the certificate that should be retrieved. * @return ://from w w w . j a v a 2 s. c om */ public ResponseCode updateCertificate(String certificate, String alias) throws CertificateManagementException { InputStream certificateStream = null; try { File trustStoreFile = new File(TRUST_STORE); localTrustStoreStream = new FileInputStream(trustStoreFile); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(localTrustStoreStream, TRUST_STORE_PASSWORD); if (trustStore.getCertificate(alias) == null) { log.error("Could not update the certificate. The certificate for alias '" + alias + "' is not found" + " in the trust store."); return ResponseCode.CERTIFICATE_NOT_FOUND; } //Generate the certificate from the input string. byte[] cert = (Base64.decodeBase64(certificate.getBytes(CHARSET_UTF_8))); certificateStream = new ByteArrayInputStream(cert); if (certificateStream.available() == 0) { log.error("Certificate is empty for the provided alias " + alias); return ResponseCode.INTERNAL_SERVER_ERROR; } CertificateFactory certificateFactory = CertificateFactory.getInstance(CERTIFICATE_TYPE); Certificate newCertificate = certificateFactory.generateCertificate(certificateStream); X509Certificate x509Certificate = (X509Certificate) newCertificate; if (x509Certificate.getNotAfter().getTime() <= System.currentTimeMillis()) { log.error("Could not update the certificate. The certificate expired."); return ResponseCode.CERTIFICATE_EXPIRED; } // If the certificate is not expired, delete the existing certificate and add the new cert. trustStore.deleteEntry(alias); //Store the certificate in the trust store. trustStore.setCertificateEntry(alias, newCertificate); fileOutputStream = new FileOutputStream(trustStoreFile); trustStore.store(fileOutputStream, TRUST_STORE_PASSWORD); } catch (IOException e) { throw new CertificateManagementException("Error updating certificate.", e); } catch (CertificateException e) { throw new CertificateManagementException("Error generating the certificate.", e); } catch (NoSuchAlgorithmException e) { throw new CertificateManagementException("Error loading the keystore.", e); } catch (KeyStoreException e) { throw new CertificateManagementException("Error updating the certificate in the keystore.", e); } finally { closeStreams(fileOutputStream, certificateStream, localTrustStoreStream); } return ResponseCode.SUCCESS; }