List of usage examples for java.security KeyStore setCertificateEntry
public final void setCertificateEntry(String alias, Certificate cert) throws KeyStoreException
From source file:gov.nih.nci.cacisweb.action.SecureFTPAddAction.java
@Override public String execute() throws Exception { log.debug("execute() - START"); String secureFTPPropertyFileLocation = CaCISUtil .getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECFTP_PROPERTIES_FILE_LOCATION); String secureFTPKeystoreLocation = CaCISUtil.getPropertyFromPropertiesFile(secureFTPPropertyFileLocation, CaCISUtil.getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECFTP_TRUSTSTORE_LOCATION_PROP_NAME)); String secureFTPKeystorePassword = CaCISUtil.getPropertyFromPropertiesFile(secureFTPPropertyFileLocation, CaCISUtil.getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECFTP_TRUSTSTORE_PASSWORD_PROP_NAME)); try {/*from w w w. j a v a 2s . c o m*/ CaCISUtil caCISUtil = new CaCISUtil(); KeyStore keystore = caCISUtil.getKeystore(secureFTPKeystoreLocation, CaCISWebConstants.COM_KEYSTORE_TYPE_JKS, secureFTPKeystorePassword); if (keystore.containsAlias(secureFTPBean.getCertificateAlias())) { log.error(getText("secureFTPBean.duplicateKey")); addFieldError("secureFTPBean.certificateAlias", getText("secureFTPBean.duplicateKey")); } if (StringUtils.contains(secureFTPBean.getCertificateAlias(), "ftps")) { if (StringUtils.isBlank(secureFTPBean.getCertificateFileName())) { log.error(getText("secureFTPBean.certificateRequired")); addFieldError("secureFTPBean.certificateFileName", getText("secureFTPBean.certificateRequired")); caCISUtil.releaseKeystore(); return INPUT; } else { caCISUtil.releaseKeystore(); FileInputStream certificateStream = new FileInputStream(secureFTPBean.getCertificate()); CertificateFactory cf = CertificateFactory.getInstance("X.509"); java.security.cert.Certificate cert = cf.generateCertificate(certificateStream); // Add the certificate keystore.setCertificateEntry(secureFTPBean.getCertificateAlias(), cert); // Save the new keystore contents FileOutputStream out = new FileOutputStream(new File(secureFTPKeystoreLocation)); keystore.store(out, secureFTPKeystorePassword.toCharArray()); out.close(); } } // add the new entry to FTP configuration properties file PropertiesConfiguration config = new PropertiesConfiguration( CaCISUtil.getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECFTP_CONFIG_FILE_LOCATION)); config.setProperty(secureFTPBean.getCertificateAlias(), ""); config.save(); } catch (KeystoreInstantiationException kie) { log.error(kie.getMessage()); addActionError(getText("exception.keystoreInstantiation")); return ERROR; } catch (CertificateException ce) { log.error(CaCISUtil.getStackTrace(ce)); addActionError(getText("exception.certification")); return INPUT; } addActionMessage(getText("secureFTPBean.addCertificateSuccessful")); log.debug("execute() - END"); return SUCCESS; }
From source file:org.mule.transport.ldap.util.DSManager.java
public synchronized void start(final boolean allowAnon) throws Exception { if (running) { logger.debug("start() called while already running"); if (checkSocketNotConnected()) { logger.debug("start() forced"); } else {//w w w . jav a2 s . c o m logger.debug("DS is already running, stop it, then start it."); try { stop(); } catch (final Exception e) { // TODO: handle exception } // throw new IllegalStateException("DS already running on port " // + port); } } logger.debug("DS is starting ..."); port = 10389; directoryService = new DefaultDirectoryService(); directoryService.setShutdownHookEnabled(false); // directoryService.getChangeLog().setEnabled(true); directoryService.setAllowAnonymousAccess(allowAnon); socketAcceptor = new SocketAcceptor(null); ldapService = new LdapService(); ldapService.setSocketAcceptor(socketAcceptor); ldapService.setDirectoryService(directoryService); ldapService.setIpPort(port); // ldapService.setIpAddress("gkar.kerb.de"); // ldapService.setAccessControlEnabled(false); // ldapService.setShutdownHookEnabled(false); ldapService.setAllowAnonymousAccess(allowAnon); // ldapService.getLdapsConfiguration().setIpPort(10636); // ldapService.getLdapsConfiguration().setEnabled(true); // ldapService.getLdapsConfiguration().setLdapsCertificateFile(new // File("src/test/resources/ldaps-server-cert.jks")); // ldapService.getLdapsConfiguration().setIpPort(10636); setupSaslMechanisms(ldapService); // S ldapSService = new LdapService(); ldapSService.setSocketAcceptor(socketAcceptor); ldapSService.setDirectoryService(directoryService); ldapSService.setIpPort(10636); ldapSService.setEnableLdaps(true); setupSaslMechanisms(ldapSService); // ldapSService.setConfidentialityRequired(true); ldapSService.setConfidentialityRequired(true); // ldapService.setIpAddress("gkar.kerb.de"); // ldapService.setAccessControlEnabled(false); // ldapService.setShutdownHookEnabled(false); ldapSService.setAllowAnonymousAccess(allowAnon); // ldapService.getLdapsConfiguration().setIpPort(10636); // ldapService.getLdapsConfiguration().setEnabled(true); // ldapService.getLdapsConfiguration().setLdapsCertificateFile(new // File("src/test/resources/ldaps-server-cert.jks")); // ldapService.getLdapsConfiguration().setIpPort(10636); setupSaslMechanisms(ldapSService); doDelete(directoryService.getWorkingDirectory()); directoryService.startup(); // java.security.cert.X509Certificate cert = // TlsKeyGenerator.getCertificate(directoryService.getAdminSession().lookup(new // LdapDN("uid=admin,ou=system")).getOriginalEntry()); final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(new FileInputStream("src/test/resources/truststore_2.jks"), "changeit".toCharArray()); // java.security.cert.X509Certificate testcert = // (java.security.cert.X509Certificate) ks.getCertificate("test"); // logger.debug(testcert); // directoryService.getAdminSession().lookup(new // LdapDN("uid=admin,ou=system")).getOriginalEntry().put("userCertificate",testcert.getEncoded()); // logger.debug("type: "+testcert.getType()); final java.security.cert.X509Certificate cert = TlsKeyGenerator.getCertificate( directoryService.getAdminSession().lookup(new LdapDN("uid=admin,ou=system")).getOriginalEntry()); ks.setCertificateEntry("apachetmp", cert); final File tmpKs = new File("target/truststore_tmp.jks"); if (tmpKs.exists()) { boolean del = tmpKs.delete(); if (!del) { logger.error("Unable to delete " + tmpKs.getAbsolutePath()); // throw new Exception("Unable to delete // "+tmpKs.getAbsolutePath()); } } ks.store(new FileOutputStream("target/truststore_tmp.jks"), "changeit".toCharArray()); logger.debug(cert); // TODO shouldn't this be before calling configureLdapServer() ??? ldapService.addExtendedOperationHandler(new StartTlsHandler()); ldapService.addExtendedOperationHandler(new StoredProcedureExtendedOperationHandler()); ldapService.start(); ldapSService.addExtendedOperationHandler(new StartTlsHandler()); // ldapSService.add( new LdapsInitializer() ); ldapSService.addExtendedOperationHandler(new StoredProcedureExtendedOperationHandler()); ldapSService.start(); // dn: uid=admin,ou=system setContexts(ServerDNConstants.ADMIN_SYSTEM_DN, "secret"); setUpPartition(); importLdif(IOUtils.getResourceAsStream("examplecom.ldif", this.getClass())); final Attributes attrs = new BasicAttributes(); attrs.put(new BasicAttribute("userCertificate", "")); // sysRoot.modifyAttributes("uid=admin",LdapContext.REPLACE_ATTRIBUTE,attrs); logger.debug(rootDSE.getAuthenticatedPrincipal()); logger.debug(rootDSE.getAuthenticationLevel()); logger.debug(rootDSE.getEffectivePrincipal()); logger.debug(rootDSE.toString()); running = true; logger.debug("DS now started!"); }
From source file:org.wso2.carbon.security.keystore.KeyStoreAdmin.java
public void importCertToStore(String fileName, String certData, String keyStoreName) throws SecurityConfigException { try {/* w ww. ja v a 2s . co m*/ if (keyStoreName == null) { throw new SecurityConfigException("Key Store name can't be null"); } KeyStoreManager keyMan = KeyStoreManager.getInstance(tenantId); KeyStore ks = keyMan.getKeyStore(keyStoreName); byte[] bytes = Base64.decode(certData); CertificateFactory factory = CertificateFactory.getInstance("X.509"); X509Certificate cert; try { cert = (X509Certificate) factory.generateCertificate(new ByteArrayInputStream(bytes)); } catch (CertificateException e) { log.error(e.getMessage(), e); throw new SecurityConfigException("Invalid format of the provided certificate file"); } if (ks.getCertificateAlias(cert) != null) { // We already have this certificate in the key store - ignore // adding it twice return; } ks.setCertificateEntry(fileName, cert); keyMan.updateKeyStore(keyStoreName, ks); } catch (SecurityConfigException e) { throw e; } catch (Exception e) { String msg = "Error when importing cert to the keyStore"; log.error(msg, e); throw new SecurityConfigException(msg, e); } }
From source file:self.philbrown.droidQuery.Ajax.java
protected TaskResponse doInBackground(Void... arg0) { if (this.isCancelled) return null; //if synchronous, block on the background thread until ready. Then call beforeSend, etc, before resuming. if (!beforeSendIsAsync) { try {//from w w w .j av a2s. c o m mutex.acquire(); } catch (InterruptedException e) { Log.w("AjaxTask", "Synchronization Error. Running Task Async"); } final Thread asyncThread = Thread.currentThread(); isLocked = true; mHandler.post(new Runnable() { @Override public void run() { if (options.beforeSend() != null) { if (options.context() != null) options.beforeSend().invoke($.with(options.context()), options); else options.beforeSend().invoke(null, options); } if (options.isAborted()) { cancel(true); return; } if (options.global()) { synchronized (globalTasks) { if (globalTasks.isEmpty()) { $.ajaxStart(); } globalTasks.add(Ajax.this); } $.ajaxSend(); } else { synchronized (localTasks) { localTasks.add(Ajax.this); } } isLocked = false; LockSupport.unpark(asyncThread); } }); if (isLocked) LockSupport.park(); } //here is where to use the mutex //handle cached responses Object cachedResponse = AjaxCache.sharedCache().getCachedResponse(options); //handle ajax caching option if (cachedResponse != null && options.cache()) { Success s = new Success(cachedResponse); s.reason = "cached response"; s.allHeaders = null; return s; } if (connection == null) { try { String type = options.type(); URL url = new URL(options.url()); if (type == null) { type = "GET"; } if (type.equalsIgnoreCase("CUSTOM")) { try { connection = options.customConnection(); } catch (Exception e) { connection = null; } if (connection == null) { Log.w("droidQuery.ajax", "CUSTOM type set, but AjaxOptions.customRequest is invalid. Defaulting to GET."); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); } } else { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(type); if (type.equalsIgnoreCase("POST") || type.equalsIgnoreCase("PUT")) { connection.setDoOutput(true); } } } catch (Throwable t) { if (options.debug()) t.printStackTrace(); Error e = new Error(null); AjaxError error = new AjaxError(); error.connection = connection; error.options = options; e.status = 0; e.reason = "Bad Configuration"; error.status = e.status; error.reason = e.reason; error.response = e.response; e.allHeaders = new Headers(); e.error = error; return e; } } Map<String, Object> args = new HashMap<String, Object>(); args.put("options", options); args.put("request", null); args.put("connection", connection); EventCenter.trigger("ajaxPrefilter", args, null); if (options.headers() != null) { if (options.headers().authorization() != null) { options.headers() .authorization(options.headers().authorization() + " " + options.getEncodedCredentials()); } else if (options.username() != null) { //guessing that authentication is basic options.headers().authorization("Basic " + options.getEncodedCredentials()); } for (Entry<String, String> entry : options.headers().map().entrySet()) { connection.setRequestProperty(entry.getKey(), entry.getValue()); } } if (options.data() != null) { try { OutputStream os = connection.getOutputStream(); os.write(options.data().toString().getBytes()); os.close(); } catch (Throwable t) { Log.w("Ajax", "Could not post data"); } } if (options.timeout() != 0) { connection.setConnectTimeout(options.timeout()); connection.setReadTimeout(options.timeout()); } if (options.trustedCertificate() != null) { Certificate ca = options.trustedCertificate(); String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = null; try { keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("ca", ca); } catch (KeyStoreException e) { if (options.debug()) e.printStackTrace(); } catch (NoSuchAlgorithmException e) { if (options.debug()) e.printStackTrace(); } catch (CertificateException e) { if (options.debug()) e.printStackTrace(); } catch (IOException e) { if (options.debug()) e.printStackTrace(); } if (keyStore == null) { Log.w("Ajax", "Could not configure trusted certificate"); } else { try { //Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); //Create an SSLContext that uses our TrustManager SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, tmf.getTrustManagers(), null); ((HttpsURLConnection) connection).setSSLSocketFactory(sslContext.getSocketFactory()); } catch (KeyManagementException e) { if (options.debug()) e.printStackTrace(); } catch (NoSuchAlgorithmException e) { if (options.debug()) e.printStackTrace(); } catch (KeyStoreException e) { if (options.debug()) e.printStackTrace(); } } } try { if (options.cookies() != null) { CookieManager cm = new CookieManager(); CookieStore cookies = cm.getCookieStore(); URI uri = URI.create(options.url()); for (Entry<String, String> entry : options.cookies().entrySet()) { HttpCookie cookie = new HttpCookie(entry.getKey(), entry.getValue()); cookies.add(uri, cookie); } connection.setRequestProperty("Cookie", TextUtils.join(",", cookies.getCookies())); } connection.connect(); final int statusCode = connection.getResponseCode(); final String message = connection.getResponseMessage(); if (options.dataFilter() != null) { if (options.context() != null) options.dataFilter().invoke($.with(options.context()), connection, options.dataType()); else options.dataFilter().invoke(null, connection, options.dataType()); } final Function function = options.statusCode().get(statusCode); if (function != null) { mHandler.post(new Runnable() { @Override public void run() { if (options.context() != null) function.invoke($.with(options.context()), statusCode, options.clone()); else function.invoke(null, statusCode, options.clone()); } }); } //handle dataType String dataType = options.dataType(); if (dataType == null) dataType = "text"; if (options.debug()) Log.i("Ajax", "dataType = " + dataType); Object parsedResponse = null; InputStream stream = null; try { if (dataType.equalsIgnoreCase("text") || dataType.equalsIgnoreCase("html")) { if (options.debug()) Log.i("Ajax", "parsing text"); stream = AjaxUtil.getInputStream(connection); parsedResponse = parseText(stream); } else if (dataType.equalsIgnoreCase("xml")) { if (options.debug()) Log.i("Ajax", "parsing xml"); if (options.customXMLParser() != null) { stream = AjaxUtil.getInputStream(connection); if (options.SAXContentHandler() != null) options.customXMLParser().parse(stream, options.SAXContentHandler()); else options.customXMLParser().parse(stream, new DefaultHandler()); parsedResponse = "Response handled by custom SAX parser"; } else if (options.SAXContentHandler() != null) { stream = AjaxUtil.getInputStream(connection); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setFeature("http://xml.org/sax/features/namespaces", false); factory.setFeature("http://xml.org/sax/features/namespace-prefixes", true); SAXParser parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); reader.setContentHandler(options.SAXContentHandler()); reader.parse(new InputSource(stream)); parsedResponse = "Response handled by custom SAX content handler"; } else { parsedResponse = parseXML(connection); } } else if (dataType.equalsIgnoreCase("json")) { if (options.debug()) Log.i("Ajax", "parsing json"); parsedResponse = parseJSON(connection); } else if (dataType.equalsIgnoreCase("script")) { if (options.debug()) Log.i("Ajax", "parsing script"); parsedResponse = parseScript(connection); } else if (dataType.equalsIgnoreCase("image")) { if (options.debug()) Log.i("Ajax", "parsing image"); stream = AjaxUtil.getInputStream(connection); parsedResponse = parseImage(stream); } else if (dataType.equalsIgnoreCase("raw")) { if (options.debug()) Log.i("Ajax", "parsing raw data"); parsedResponse = parseRawContent(connection); } } catch (ClientProtocolException cpe) { if (options.debug()) cpe.printStackTrace(); Error e = new Error(parsedResponse); AjaxError error = new AjaxError(); error.connection = connection; error.options = options; e.status = statusCode; e.reason = message; error.status = e.status; error.reason = e.reason; error.response = e.response; e.allHeaders = Headers.createHeaders(connection.getHeaderFields()); e.error = error; return e; } catch (Exception ioe) { if (options.debug()) ioe.printStackTrace(); Error e = new Error(parsedResponse); AjaxError error = new AjaxError(); error.connection = connection; error.options = options; e.status = statusCode; e.reason = message; error.status = e.status; error.reason = e.reason; error.response = e.response; e.allHeaders = Headers.createHeaders(connection.getHeaderFields()); e.error = error; return e; } finally { connection.disconnect(); try { if (stream != null) { stream.close(); } } catch (IOException e) { } } if (statusCode >= 300) { //an error occurred Error e = new Error(parsedResponse); Log.e("Ajax Test", parsedResponse.toString()); //AjaxError error = new AjaxError(); //error.request = request; //error.options = options; e.status = e.status; e.reason = e.reason; //error.status = e.status; //error.reason = e.reason; //error.response = e.response; e.allHeaders = Headers.createHeaders(connection.getHeaderFields()); //e.error = error; if (options.debug()) Log.i("Ajax", "Error " + e.status + ": " + e.reason); return e; } else { //handle ajax ifModified option List<String> lastModifiedHeaders = connection.getHeaderFields().get("last-modified"); if (lastModifiedHeaders.size() >= 1) { try { String h = lastModifiedHeaders.get(0); SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US); Date lastModified = format.parse(h); if (options.ifModified() && lastModified != null) { Date lastModifiedDate; synchronized (lastModifiedUrls) { lastModifiedDate = lastModifiedUrls.get(options.url()); } if (lastModifiedDate != null && lastModifiedDate.compareTo(lastModified) == 0) { //request response has not been modified. //Causes an error instead of a success. Error e = new Error(parsedResponse); AjaxError error = new AjaxError(); error.connection = connection; error.options = options; e.status = e.status; e.reason = e.reason; error.status = e.status; error.reason = e.reason; error.response = e.response; e.allHeaders = Headers.createHeaders(connection.getHeaderFields()); e.error = error; Function func = options.statusCode().get(304); if (func != null) { if (options.context() != null) func.invoke($.with(options.context())); else func.invoke(null); } return e; } else { synchronized (lastModifiedUrls) { lastModifiedUrls.put(options.url(), lastModified); } } } } catch (Throwable t) { Log.e("Ajax", "Could not parse Last-Modified Header", t); } } //Now handle a successful request Success s = new Success(parsedResponse); s.reason = message; s.allHeaders = Headers.createHeaders(connection.getHeaderFields()); return s; } } catch (Throwable t) { if (options.debug()) t.printStackTrace(); if (t instanceof java.net.SocketTimeoutException) { Error e = new Error(null); AjaxError error = new AjaxError(); error.connection = connection; error.options = options; error.response = e.response; e.status = 0; String reason = t.getMessage(); if (reason == null) reason = "Socket Timeout"; e.reason = reason; error.status = e.status; error.reason = e.reason; if (connection != null) e.allHeaders = Headers.createHeaders(connection.getHeaderFields()); else e.allHeaders = new Headers(); e.error = error; return e; } return null; } }
From source file:org.wso2.carbon.security.keystore.KeyStoreAdmin.java
public String importCertToStore(String certData, String keyStoreName) throws SecurityConfigException { String alias = null;//w ww.j av a2s . c o m try { if (keyStoreName == null) { throw new SecurityConfigException("Key Store name can't be null"); } KeyStoreManager keyMan = KeyStoreManager.getInstance(tenantId); KeyStore ks = keyMan.getKeyStore(keyStoreName); byte[] bytes = Base64.decode(certData); CertificateFactory factory = CertificateFactory.getInstance("X.509"); X509Certificate cert; try { cert = (X509Certificate) factory.generateCertificate(new ByteArrayInputStream(bytes)); } catch (Exception e) { throw new SecurityConfigException("Invalid format of the provided certificate file", e); } if (ks.getCertificateAlias(cert) != null) { // We already have this certificate in the key store - ignore // adding it twice return null; } alias = cert.getSubjectDN().getName(); ks.setCertificateEntry(alias, cert); keyMan.updateKeyStore(keyStoreName, ks); return alias; } catch (SecurityConfigException e) { throw e; } catch (Exception e) { String msg = "Error when importing cert to keyStore"; log.error(msg, e); throw new SecurityConfigException(msg); } }
From source file:com.wwpass.connection.WWPassConnection.java
public WWPassConnection(X509Certificate cert, PKCS8EncodedKeySpec key, int timeoutSec, String spfeAddr) throws IOException, GeneralSecurityException { timeoutMs = timeoutSec * 1000;/*from w w w . jav a 2 s . c om*/ SpfeURL = "https://" + spfeAddr + "/"; // Setting up client certificate and key X509Certificate[] chain = { cert }; KeyFactory kf = KeyFactory.getInstance("RSA"); PrivateKey privKey = kf.generatePrivate(key); KeyStore.PrivateKeyEntry pke = new KeyStore.PrivateKeyEntry(privKey, chain); //This adds no security but Java requires to password-protect the key byte[] password_bytes = new byte[16]; (new java.security.SecureRandom()).nextBytes(password_bytes); // String password = (new BASE64Encoder()).encode(password_bytes); String password = (new Base64()).encodeToString(password_bytes); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509"); KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(null); keyStore.setEntry("WWPass client key", pke, new KeyStore.PasswordProtection(password.toCharArray())); keyManagerFactory.init(keyStore, password.toCharArray()); SPFEContext = SSLContext.getInstance("TLS"); // Making rootCA certificate InputStream is = null; CertificateFactory cf; X509Certificate rootCA = null; try { is = new ByteArrayInputStream(WWPassCA_DER); cf = CertificateFactory.getInstance("X.509"); rootCA = (X509Certificate) cf.generateCertificate(is); } finally { if (is != null) { is.close(); } } //Creating TrustManager for this CA TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); KeyStore ks = KeyStore.getInstance("JKS"); ks.load(null); ks.setCertificateEntry("WWPass Root CA", rootCA); trustManagerFactory.init(ks); SPFEContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new java.security.SecureRandom()); }
From source file:it.cnr.icar.eric.common.security.KeystoreMover.java
public void move(String sourceKeystoreType, String sourceKeystorePath, String sourceKeystorePassword, String sourceAlias, String sourceKeyPassword, String destinationKeystoreType, String destinationKeystorePath, String destinationKeystorePassword, String destinationAlias, String destinationKeyPassword) throws Exception { char[] sourceKeystorePasswordArr = null; if (sourceKeystorePassword != null) { sourceKeystorePasswordArr = sourceKeystorePassword.toCharArray(); }/* w w w. ja v a 2 s. c om*/ char[] sourceKeyPasswordArr = sourceKeystorePasswordArr; if (sourceKeyPassword != null) { sourceKeyPasswordArr = sourceKeyPassword.toCharArray(); } char[] destinationKeystorePasswordArr = null; if (destinationKeystorePassword != null) { destinationKeystorePasswordArr = destinationKeystorePassword.toCharArray(); } char[] destinationKeyPasswordArr = destinationKeystorePasswordArr; if (destinationKeyPassword != null) { destinationKeyPasswordArr = destinationKeyPassword.toCharArray(); } FileInputStream in; // -------- Load source keystore to memory --------- in = new FileInputStream(sourceKeystorePath); KeyStore ksin = KeyStore.getInstance(sourceKeystoreType); ksin.load(in, sourceKeystorePasswordArr); in.close(); // -------- Load destination keystore initial contents to memory --------- KeyStore ksout = KeyStore.getInstance(destinationKeystoreType); try { in = new FileInputStream(destinationKeystorePath); ksout.load(in, destinationKeystorePasswordArr); } catch (java.io.FileNotFoundException e) { ksout.load(null, destinationKeystorePasswordArr); } finally { in.close(); } Enumeration<String> en = ksin.aliases(); while (en.hasMoreElements()) { String alias = en.nextElement(); if ((sourceAlias == null) || (sourceAlias.equalsIgnoreCase(alias))) { if (ksout.containsAlias(alias)) { log.info(CommonResourceBundle.getInstance().getString( "message.destinationKeystorePathAlreadyContains", new Object[] { destinationKeystorePath, alias })); continue; } //Use existing alias if no destinationAlias specified if (destinationAlias == null) { destinationAlias = alias; } if (ksin.isCertificateEntry(alias)) { log.debug(CommonResourceBundle.getInstance().getString("message.importingCertificate", new Object[] { alias })); ksout.setCertificateEntry(destinationAlias, ksin.getCertificate(alias)); } if (ksin.isKeyEntry(alias)) { log.debug(CommonResourceBundle.getInstance().getString("message.importingKey", new Object[] { alias })); Certificate[] certChain = ksin.getCertificateChain(alias); ksout.setKeyEntry(destinationAlias, ksin.getKey(alias, sourceKeyPasswordArr), destinationKeyPasswordArr, certChain); } } } //--------- Overwrite the destination keystore with new keys/certs which is a merge of source and original destination keystores-------------- FileOutputStream out = new FileOutputStream(destinationKeystorePath); ksout.store(out, destinationKeystorePasswordArr); out.close(); log.debug(CommonResourceBundle.getInstance().getString("message.keystoreCopySuccessful")); }
From source file:org.codice.ddf.security.certificate.keystore.editor.KeystoreEditor.java
private boolean importASN1CertificatesToStore(KeyStore store, boolean setEntry, ASN1Set certificates) throws KeystoreEditorException { Enumeration certificateEnumeration = certificates.getObjects(); try {// w w w. ja v a 2s. co m while (certificateEnumeration.hasMoreElements()) { ASN1Primitive asn1Primitive = ((ASN1Encodable) certificateEnumeration.nextElement()) .toASN1Primitive(); org.bouncycastle.asn1.x509.Certificate instance = org.bouncycastle.asn1.x509.Certificate .getInstance(asn1Primitive); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC"); Certificate certificate = certificateFactory .generateCertificate(new ByteArrayInputStream(instance.getEncoded())); X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate).getSubject(); RDN cn = x500name.getRDNs(BCStyle.CN)[0]; store.setCertificateEntry(IETFUtils.valueToString(cn.getFirst().getValue()), certificate); setEntry = true; } } catch (CertificateException | NoSuchProviderException | KeyStoreException | IOException e) { throw new KeystoreEditorException("Unable to import ASN1 certificates to store", e); } return setEntry; }
From source file:com.qut.middleware.crypto.impl.CryptoProcessorImpl.java
public KeyStore addKeyPair(KeyStore keyStore, String keyStorePassphrase, KeyPair keyPair, String keyPairName, String keyPairPassphrase, String keyPairSubjectDN) throws CryptoException { logger.debug("Adding key pair to existing key store"); try {//w w w . j av a2s . c om // Create the public key certificate for storage in the key store. X509Certificate cert = generateV3Certificate(keyPair, keyPairSubjectDN); X500PrivateCredential privateCredentials = new X500PrivateCredential(cert, keyPair.getPrivate(), keyPairName); Certificate[] certChain = new X509Certificate[1]; certChain[0] = privateCredentials.getCertificate(); // Load our generated key store up. They all have the same password, which we set. keyStore.load(null, keyStorePassphrase.toCharArray()); /* Add certificate which contains the public key and set the private key as a key entry in the key store */ keyStore.setCertificateEntry(privateCredentials.getAlias(), privateCredentials.getCertificate()); keyStore.setKeyEntry(privateCredentials.getAlias(), keyPair.getPrivate(), keyPairPassphrase.toCharArray(), certChain); return keyStore; } catch (NoSuchAlgorithmException e) { this.logger.error("NoSuchAlgorithmException thrown, " + e.getLocalizedMessage()); this.logger.debug(e.toString()); throw new CryptoException(e.getLocalizedMessage(), e); } catch (CertificateException e) { this.logger.error("CertificateException thrown, " + e.getLocalizedMessage()); this.logger.debug(e.toString()); throw new CryptoException(e.getLocalizedMessage(), e); } catch (KeyStoreException e) { this.logger.error("KeyStoreException thrown, " + e.getLocalizedMessage()); this.logger.debug(e.toString()); throw new CryptoException(e.getLocalizedMessage(), e); } catch (IOException e) { this.logger.error("IOException thrown, " + e.getLocalizedMessage()); this.logger.debug(e.toString()); throw new CryptoException(e.getLocalizedMessage(), e); } }
From source file:io.swagger.client.ApiClient.java
/** * Apply SSL related settings to httpClient according to the current values of * verifyingSsl and sslCaCert./*from w ww . j a va 2 s .c o m*/ */ private void applySslSettings() { try { KeyManager[] keyManagers = null; TrustManager[] trustManagers = null; HostnameVerifier hostnameVerifier = null; if (!verifyingSsl) { TrustManager trustAll = new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } }; SSLContext sslContext = SSLContext.getInstance("TLS"); trustManagers = new TrustManager[] { trustAll }; hostnameVerifier = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; } else if (sslCaCert != null) { char[] password = null; // Any password will work. CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(sslCaCert); if (certificates.isEmpty()) { throw new IllegalArgumentException("expected non-empty set of trusted certificates"); } KeyStore caKeyStore = newEmptyKeyStore(password); int index = 0; for (Certificate certificate : certificates) { String certificateAlias = "ca" + Integer.toString(index++); caKeyStore.setCertificateEntry(certificateAlias, certificate); } TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(caKeyStore); trustManagers = trustManagerFactory.getTrustManagers(); } if (keyManagers != null || trustManagers != null) { SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagers, trustManagers, new SecureRandom()); httpClient.setSslSocketFactory(sslContext.getSocketFactory()); } else { httpClient.setSslSocketFactory(null); } httpClient.setHostnameVerifier(hostnameVerifier); } catch (GeneralSecurityException e) { throw new RuntimeException(e); } }