List of usage examples for java.security KeyStore setCertificateEntry
public final void setCertificateEntry(String alias, Certificate cert) throws KeyStoreException
From source file:org.opendaylight.aaa.cert.impl.ODLMdsalKeyTool.java
public KeyStore addCertificate(final KeyStore keyStore, final String certificate, final String alias, final boolean deleteOld) { try {//from www .j a va2 s . c o m final X509Certificate newCert = getCertificate(certificate); if (keyStore.isCertificateEntry(alias) && deleteOld) { keyStore.deleteEntry(alias); } if (newCert != null) { keyStore.setCertificateEntry(alias, newCert); } else { LOG.warn("{} Not a valid certificate {}", alias, certificate); return null; } return keyStore; } catch (final KeyStoreException e) { LOG.error("failed to add certificate", e); return null; } }
From source file:com.openshift.restclient.ClientBuilder.java
private TrustManagerFactory initTrustManagerFactory(String alias, X509Certificate cert, Collection<X509Certificate> certs) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException { TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); if (alias != null && (cert != null || certs != null)) { KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); // need this load to initialize the key store, and allow for the subsequent set certificate entry ks.load(null, null);//from w ww .j a v a 2 s . co m if (cert != null) { cert.checkValidity(); ks.setCertificateEntry(alias, cert); } if (certs != null) { int i = 0; for (X509Certificate x509 : certs) { x509.checkValidity(); ks.setCertificateEntry(alias + i, x509); i++; } } // testing has proven that you can only call init() once for a TrustManagerFactory wrt loading certs // from the KeyStore ... subsequent KeyStore.setCertificateEntry / TrustManagerFactory.init calls are // ignored. // So if a specific cert is required to validate this connection's communication with the server, add it up front // in the ctor. trustManagerFactory.init(ks); } else { trustManagerFactory.init((KeyStore) null); } return trustManagerFactory; }
From source file:org.opendaylight.aaa.cert.impl.ODLKeyTool.java
public boolean createKeyStoreImportCert(final String keyStoreName, final String keyStorePwd, final String certFile, final String alias) { KeyStore trustKeyStore; try {/*from ww w. j a v a 2s . com*/ trustKeyStore = KeyStore.getInstance("JKS"); trustKeyStore.load(null, keyStorePwd.toCharArray()); if (KeyStoreConstant.checkKeyStoreFile(certFile)) { final String certificate = KeyStoreConstant.readFile(certFile); final X509Certificate newCert = getCertificate(certificate); trustKeyStore.setCertificateEntry(alias, newCert); } trustKeyStore.store(new FileOutputStream(workingDir + keyStoreName), keyStorePwd.toCharArray()); LOG.info("{} is created", keyStoreName); return true; } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) { LOG.error("Failed to create keystore {}", keyStoreName, e); return false; } }
From source file:org.ejbca.core.protocol.ocsp.OCSPUnidClient.java
private SSLSocketFactory getSSLFactory() throws IOException, NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException, CertificateException, KeyManagementException { final KeyManager km[]; final TrustManager tm[]; // Put the key and certs in the user keystore (if available) if (this.ks != null) { final KeyManagerFactory kmf; kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(this.ks, this.passphrase.toCharArray()); km = kmf.getKeyManagers();//from ww w .j a v a2 s .c o m } else { km = null; } // Now make a truststore to verify the server if (this.certChain != null && this.certChain.length > 0) { final KeyStore trustks = KeyStore.getInstance("jks"); trustks.load(null, "foo123".toCharArray()); // add trusted CA cert trustks.setCertificateEntry("trusted", this.certChain[this.certChain.length - 1]); final TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); tmf.init(trustks); tm = tmf.getTrustManagers(); } else { tm = null; } if (km == null && tm == null) { return (SSLSocketFactory) SSLSocketFactory.getDefault(); } final SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(km, tm, null); return ctx.getSocketFactory(); }
From source file:net.shirayu.android.WlanLogin.MyHttpClient.java
public static KeyStore loadKeyStore(Context context) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException, NoSuchProviderException { /*/*from www. ja v a 2 s.com*/ * Original implementation. I refer the following sites about the default keystore. http://wiki.livedoor.jp/syo1976/d/javassl http://d.hatena.ne.jp/Kazzz/20110319/p1 */ KeyStore certstore; if (Integer.valueOf(Build.VERSION.SDK) >= 14) { // load from unified key store certstore = KeyStore.getInstance("AndroidCAStore"); certstore.load(null, null); } else { certstore = KeyStore.getInstance(KeyStore.getDefaultType()); certstore.load(new FileInputStream(System.getProperty("javax.net.ssl.trustStore")), null); //load default keystore } //load self_signed_certificate? SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); final Boolean use_self_signed_certificate = sharedPreferences.getBoolean("use_self_signed_certificate", false); if (use_self_signed_certificate) { final Boolean use_folder = sharedPreferences.getBoolean("use_self_signed_certificate_folder", false); final String filename = sharedPreferences.getString("self_signed_certificate_path", "//"); File myfile = new File(filename); if (use_folder) { for (File file : new File(myfile.getParent()).listFiles()) { if (file.isDirectory()) continue; FileInputStream stream = new FileInputStream(file); X509Certificate cert = MyHttpClient.readPem(stream); certstore.setCertificateEntry(file.getName(), cert); } } else { FileInputStream stream = new FileInputStream(myfile); X509Certificate cert = MyHttpClient.readPem(stream); certstore.setCertificateEntry(myfile.getName(), cert); } ; } ; return certstore; }
From source file:org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.enrollment.EnrollmentManager.java
private void storeCertificateToStore(String alias, Certificate certificate) { KeyStore keyStore; try {/* www .j a v a 2 s . c om*/ keyStore = KeyStore.getInstance(AgentConstants.DEVICE_KEYSTORE_TYPE); keyStore.setCertificateEntry(alias, certificate); keyStore.store(new FileOutputStream(AgentConstants.DEVICE_KEYSTORE), AgentConstants.DEVICE_KEYSTORE_PASSWORD.toCharArray()); } catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | IOException e) { log.error(AgentConstants.LOG_APPENDER + "An error occurred whilst trying to store the Certificate received from the SCEP " + "Enrollment."); log.error(AgentConstants.LOG_APPENDER + e); log.warn(AgentConstants.LOG_APPENDER + "SCEP Certificate was not stored in the keystore; " + "Hence the device will be re-enrolled during next restart."); } }
From source file:org.ejbca.util.keystore.KeyTools.java
/** * Creates JKS-file that can be used with JDK. The alias for the private key is set to * 'privateKey' and the private key password is null. * * @param alias the alias used for the key entry * @param privKey RSA private key/*from ww w . ja v a 2 s .co m*/ * @param password user's password * @param cert user certificate * @param cachain CA-certificate chain or null if only one cert in chain, in that case use * 'cert'. * * @return KeyStore containing JKS-keystore * * @exception Exception if input parameters are not OK or certificate generation fails */ public static KeyStore createJKS(final String alias, final PrivateKey privKey, final String password, final X509Certificate cert, final Certificate[] cachain) throws Exception { if (log.isTraceEnabled()) { log.trace(">createJKS: alias=" + alias + ", privKey, cert=" + CertTools.getSubjectDN(cert) + ", cachain.length=" + ((cachain == null) ? 0 : cachain.length)); } final String caAlias = "cacert"; // Certificate chain if (cert == null) { throw new IllegalArgumentException("Parameter cert cannot be null."); } int len = 1; if (cachain != null) { len += cachain.length; } final Certificate[] chain = new Certificate[len]; chain[0] = cert; if (cachain != null) { for (int i = 0; i < cachain.length; i++) { chain[i + 1] = cachain[i]; } } // store the key and the certificate chain final KeyStore store = KeyStore.getInstance("JKS"); store.load(null, null); // First load the key entry final X509Certificate[] usercert = new X509Certificate[1]; usercert[0] = cert; store.setKeyEntry(alias, privKey, password.toCharArray(), usercert); // Add the root cert as trusted if (cachain != null) { if (!CertTools.isSelfSigned((X509Certificate) cachain[cachain.length - 1])) { throw new IllegalArgumentException("Root cert is not self-signed."); } store.setCertificateEntry(caAlias, cachain[cachain.length - 1]); } // Set the complete chain log.debug("Storing cert chain of length " + chain.length); store.setKeyEntry(alias, privKey, password.toCharArray(), chain); if (log.isTraceEnabled()) { log.trace("<createJKS: alias=" + alias + ", privKey, cert=" + CertTools.getSubjectDN(cert) + ", cachain.length=" + ((cachain == null) ? 0 : cachain.length)); } return store; }
From source file:com.mhise.util.MHISEUtil.java
public static KeyStore getServerKeyStore(String url) { KeyStore ks = null; try {//from w ww .j a v a 2s . c o m MHISETrustManager.allowAllSSL(); HttpsURLConnection connection = (HttpsURLConnection) (new URL(url)).openConnection(); connection.connect(); Certificate[] certs = connection.getServerCertificates(); ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null, null); ks.setCertificateEntry("servercert", certs[0]); Log.i("MHISEUtil-->getServerKeyStore", certs[0].getPublicKey().toString()); } catch (Exception e) { Logger.debug("MHISEUtil-->getServerKeyStore", "Exception" + e); e.printStackTrace(); } return ks; }
From source file:io.fabric8.kubernetes.api.KubernetesFactory.java
private void configureCaCert(WebClient webClient) { try (InputStream pemInputStream = getInputStreamFromDataOrFile(caCertData, caCertFile)) { CertificateFactory certFactory = CertificateFactory.getInstance("X509"); X509Certificate cert = (X509Certificate) certFactory.generateCertificate(pemInputStream); KeyStore trustStore = KeyStore.getInstance("JKS"); trustStore.load(null);//from w ww. jav a 2 s.c o m String alias = cert.getSubjectX500Principal().getName(); trustStore.setCertificateEntry(alias, cert); TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(trustStore); HTTPConduit conduit = WebClient.getConfig(webClient).getHttpConduit(); TLSClientParameters params = conduit.getTlsClientParameters(); if (params == null) { params = new TLSClientParameters(); conduit.setTlsClientParameters(params); } TrustManager[] existingTrustManagers = params.getTrustManagers(); TrustManager[] trustManagers; if (existingTrustManagers == null || ArrayUtils.isEmpty(existingTrustManagers)) { trustManagers = trustManagerFactory.getTrustManagers(); } else { trustManagers = (TrustManager[]) ArrayUtils.addAll(existingTrustManagers, trustManagerFactory.getTrustManagers()); } params.setTrustManagers(trustManagers); } catch (Exception e) { log.error("Could not create trust manager for " + caCertFile, e); } }
From source file:org.apache.hadoop.io.crypto.bee.RestClient.java
private InputStream httpsWithCertificate(final URL url) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, KeyManagementException { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null);// Make an empty store CertificateFactory cf = CertificateFactory.getInstance("X.509"); FileInputStream fis = new FileInputStream(BeeConstants.BEE_HTTPS_CERTIFICATE_DEFAULT_PATH); BufferedInputStream bis = new BufferedInputStream(fis); while (bis.available() > 0) { Certificate cert = cf.generateCertificate(bis); // System.out.println(cert.getPublicKey().toString()); trustStore.setCertificateEntry("jetty" + bis.available(), cert); }//from ww w . j a v a 2s. c o m TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(trustStore); SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(null, tmf.getTrustManagers(), null); SSLSocketFactory sslFactory = ctx.getSocketFactory(); // Create all-trusting host name verifier HostnameVerifier allHostsValid = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { if (0 == hostname.compareToIgnoreCase(url.getHost())) { return true; } return false; } }; // Install the all-trusting host verifier HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection(); urlConnection.setSSLSocketFactory(sslFactory); return urlConnection.getInputStream(); }