List of usage examples for java.security KeyStore getDefaultType
public static final String getDefaultType()
From source file:com.vimukti.accounter.license.LicenseManager.java
private PrivateKey getPrivateKey() { Key key = null;//from w ww. ja va 2 s. c o m try { FileInputStream is = new FileInputStream( ServerConfiguration.getConfig() + File.separator + "license.keystore"); KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); String password = ServerConfiguration.getLicenseKeystorePWD(); keystore.load(is, password.toCharArray()); key = keystore.getKey(ServerConfiguration.getLicenseAlias(), password.toCharArray()); } catch (NoSuchAlgorithmException e) { throw new LicenseException(e); } catch (CertificateException e) { throw new LicenseException(e); } catch (IOException e) { throw new LicenseException(e); } catch (UnrecoverableKeyException e) { throw new LicenseException(e); } catch (KeyStoreException e) { throw new LicenseException(e); } return (PrivateKey) key; }
From source file:srl.distributed.client.Client.java
private DefaultHttpClient getNewHttpClient() { try {/*from ww w .j a v a2 s . c o m*/ KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLSocketFactory sf = new InsecureSSLSocketFactory(trustStore); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", sf, 443)); ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); return new DefaultHttpClient(ccm, params); } catch (Exception e) { return new DefaultHttpClient(); } }
From source file:com.verisign.epp.serverstub.LaunchDomainHandler.java
/** * Loads the trust store file and the Certificate Revocation List (CRL) file * into the <code>PKIXParameters</code> used to verify the certificate chain * and verify the certificate against the CRL. Both the Java Trust Store is * loaded with the trusted root CA certificates (trust anchors) and the CRL * file is attempted to be loaded to identify the revoked certificates. If * the CRL file is not found, then no CRL checking will be done. * //w w w .j a v a 2s. c o m * @param aTrustStoreName * Trust store file name * @param aCrls * List of Certificate Revocation List (CRL) file names * * @return Initialized <code>PKIXParameters</code> instance. * * @throws Exception * Error initializing the PKIX parameters */ private PKIXParameters loadPKIXParameters(String aTrustStoreName, List<String> aCrls) throws Exception { cat.debug("LaunchDomainHandler.loadPKIXParameters(String, String): enter"); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream trustStoreFile = new FileInputStream(aTrustStoreName); trustStore.load(trustStoreFile, null); trustStoreFile.close(); cat.debug("LaunchDomainHandler.loadPKIXParameters(String, String): truststore = " + aTrustStoreName); PKIXParameters pkixParameters = new PKIXParameters(trustStore); CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); Collection crlContentsList = new ArrayList(); for (String currCrl : aCrls) { File crlFile = new File(currCrl); if (crlFile.exists()) { InputStream inStream = null; try { cat.debug("LaunchDomainHandler.loadPKIXParameters(String, String): adding CRL " + currCrl); inStream = new FileInputStream(currCrl); crlContentsList.add(certFactory.generateCRL(inStream)); } finally { if (inStream != null) { inStream.close(); } } } else { throw new EPPException("CRL file " + currCrl + " does not exist."); } } // At least 1 CRL was loaded if (crlContentsList.size() != 0) { List<CertStore> certStores = new ArrayList<CertStore>(); certStores.add(CertStore.getInstance("Collection", new CollectionCertStoreParameters(crlContentsList))); pkixParameters.setCertStores(certStores); pkixParameters.setRevocationEnabled(true); cat.debug("LaunchDomainHandler.loadPKIXParameters(String, String): Revocation enabled"); } else { pkixParameters.setRevocationEnabled(false); cat.debug("LaunchDomainHandler.loadPKIXParameters(String, String): Revocation disabled"); } cat.debug("LaunchDomainHandler.loadPKIXParameters(String, String): exit"); return pkixParameters; }
From source file:org.apache.ambari.server.controller.internal.URLStreamProvider.java
protected HttpsURLConnection getSSLConnection(String spec) throws IOException { if (sslSocketFactory == null) { synchronized (this) { if (sslSocketFactory == null) { try { FileInputStream in = new FileInputStream(new File(path)); KeyStore store = KeyStore.getInstance(type == null ? KeyStore.getDefaultType() : type); store.load(in, password.toCharArray()); in.close();//from ww w. j a va 2s . com TrustManagerFactory tmf = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(store); SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); sslSocketFactory = context.getSocketFactory(); } catch (Exception e) { throw new IOException("Can't get connection.", e); } } } } HttpsURLConnection connection = (HttpsURLConnection) (new URL(spec).openConnection()); connection.setSSLSocketFactory(sslSocketFactory); return connection; }
From source file:org.jsslutils.extra.apachetomcat5.JSSLutilsJSSESocketFactory.java
/** * Reads the keystore and initializes the SSL socket factory. *///from w w w.j av a 2 s. co m void init() throws IOException { try { String clientAuthStr = (String) attributes.get("clientauth"); if ("true".equalsIgnoreCase(clientAuthStr) || "yes".equalsIgnoreCase(clientAuthStr)) { requireClientAuth = true; } else if ("want".equalsIgnoreCase(clientAuthStr)) { wantClientAuth = true; } // SSL protocol variant (e.g., TLS, SSL v3, etc.) String protocol = (String) attributes.get("protocol"); if (protocol == null) { protocol = defaultProtocol; } String keyPassAttr = (String) attributes.get("keypass"); KeyStoreLoader ksl = KeyStoreLoader.getKeyStoreDefaultLoader(); String keystoreFileAttr = (String) attributes.get("keystoreFile"); if (keystoreFileAttr == null) keystoreFileAttr = (String) attributes.get("keystore"); if (keystoreFileAttr != null) { ksl.setKeyStorePath(keystoreFileAttr.length() == 0 ? null : keystoreFileAttr); } String keystorePassAttr = (String) attributes.get("keystorePass"); if (keystorePassAttr == null) keystorePassAttr = keyPassAttr; if (keystorePassAttr != null) ksl.setKeyStorePassword(keystorePassAttr); String keystoreTypeAttr = (String) attributes.get("keystoreType"); ksl.setKeyStoreType(keystoreTypeAttr != null ? keystoreTypeAttr : KeyStore.getDefaultType()); String keystoreProviderAttr = (String) attributes.get("keystoreProvider"); if (keystoreProviderAttr != null) { ksl.setKeyStoreProvider(keystoreProviderAttr.length() == 0 ? null : keystoreProviderAttr); } KeyStoreLoader tsl = KeyStoreLoader.getTrustStoreDefaultLoader(); String truststoreFileAttr = (String) attributes.get("truststoreFile"); if (truststoreFileAttr != null) { tsl.setKeyStorePath(truststoreFileAttr.length() == 0 ? null : truststoreFileAttr); } String truststorePassAttr = (String) attributes.get("truststorePass"); if (truststorePassAttr != null) tsl.setKeyStorePassword(truststorePassAttr); String truststoreTypeAttr = (String) attributes.get("truststoreType"); tsl.setKeyStoreType(truststoreTypeAttr != null ? truststoreTypeAttr : KeyStore.getDefaultType()); String truststoreProviderAttr = (String) attributes.get("truststoreProvider"); if (truststoreProviderAttr != null) { tsl.setKeyStoreProvider(truststoreProviderAttr.length() == 0 ? null : truststoreProviderAttr); } KeyStore keyStore = ksl.loadKeyStore(); KeyStore trustStore = tsl.loadKeyStore(); PKIXSSLContextFactory sslContextFactory = new PKIXSSLContextFactory(keyStore, keyPassAttr, trustStore); String crlURLsAttr = (String) attributes.get("crlURLs"); if (crlURLsAttr != null) { StringTokenizer st = new StringTokenizer(crlURLsAttr, " "); while (st.hasMoreTokens()) { String crlUrl = st.nextToken(); sslContextFactory.addCrl(crlUrl); } } String acceptAnyCert = (String) attributes.get("acceptAnyCert"); if ("true".equalsIgnoreCase(acceptAnyCert) || "yes".equalsIgnoreCase(acceptAnyCert)) { sslContextFactory.setTrustManagerWrapper(new TrustAllClientsWrappingTrustManager.Wrapper()); } else { String acceptProxyCertsAttr = (String) attributes.get("acceptProxyCerts"); if ((acceptProxyCertsAttr != null) && (acceptProxyCertsAttr.length() > 0)) { boolean allowLegacy = false; boolean allowPreRfc = false; boolean allowRfc3820 = false; String[] acceptProxyTypes = acceptProxyCertsAttr.split(","); for (int i = 0; i < acceptProxyTypes.length; i++) { if ("legacy".equalsIgnoreCase(acceptProxyTypes[i].trim())) { allowLegacy = true; } if ("prerfc".equalsIgnoreCase(acceptProxyTypes[i].trim())) { allowPreRfc = true; } if ("rfc3820".equalsIgnoreCase(acceptProxyTypes[i].trim())) { allowRfc3820 = true; } } if (allowLegacy || allowPreRfc || allowRfc3820) { try { Class<?> wrapperClass = Class .forName("org.jsslutils.extra.gsi.GsiWrappingTrustManager"); Constructor<?> constructor = wrapperClass.getConstructor(Boolean.TYPE, Boolean.TYPE, Boolean.TYPE); X509TrustManagerWrapper wrapper = (X509TrustManagerWrapper) constructor .newInstance(allowLegacy, allowPreRfc, allowRfc3820); sslContextFactory.setTrustManagerWrapper(wrapper); } catch (ClassNotFoundException e) { throw new Exception( "Unable to load org.jsslutils.extra.gsi.GsiWrappingTrustManager, please put the required files on the class path.", e); } catch (NoSuchMethodException e) { throw new Exception( "Unable to load org.jsslutils.extra.gsi.GsiWrappingTrustManager, please put the required files on the class path.", e); } catch (SecurityException e) { throw new Exception( "Unable to load org.jsslutils.extra.gsi.GsiWrappingTrustManager, please put the required files on the class path.", e); } catch (ClassCastException e) { throw new Exception( "Unable to load org.jsslutils.extra.gsi.GsiWrappingTrustManager, please put the required files on the class path.", e); } } } } // Create and init SSLContext SSLContext context = sslContextFactory.buildSSLContext(protocol); // create proxy sslProxy = context.getServerSocketFactory(); // Determine which cipher suites to enable String requestedCiphers = (String) attributes.get("ciphers"); enabledCiphers = getEnabledCiphers(requestedCiphers, sslProxy.getSupportedCipherSuites()); } catch (Exception e) { if (e instanceof IOException) throw (IOException) e; throw new IOException(e.getMessage()); } }
From source file:com.mytalentfolio.h_daforum.CconnectToServer.java
/** * Creates a new instance of KeyStore from provided certificate. * /* w w w . j av a 2 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:com.sonatype.nexus.ssl.plugin.internal.TrustStoreImpl.java
private static TrustManager[] getSystemTrustManagers() throws Exception { TrustManagerFactory trustManagerFactory; String trustAlgorithm = System.getProperty("ssl.TrustManagerFactory.algorithm"); if (trustAlgorithm == null) { trustAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); }//from w ww . j a v a 2 s. c o m String trustStoreType = System.getProperty("javax.net.ssl.trustStoreType"); if (trustStoreType == null) { trustStoreType = KeyStore.getDefaultType(); } if ("none".equalsIgnoreCase(trustStoreType)) { trustManagerFactory = TrustManagerFactory.getInstance(trustAlgorithm); } else { File trustStoreFile; KeyStore trustStore; String trustStoreFileName = System.getProperty("javax.net.ssl.trustStore"); if (trustStoreFileName != null) { trustStoreFile = new File(trustStoreFileName); trustManagerFactory = TrustManagerFactory.getInstance(trustAlgorithm); final String trustStoreProvider = System.getProperty("javax.net.ssl.trustStoreProvider"); if (trustStoreProvider != null) { trustStore = KeyStore.getInstance(trustStoreType, trustStoreProvider); } else { trustStore = KeyStore.getInstance(trustStoreType); } } else { File javaHome = new File(System.getProperty("java.home")); File file = new File(javaHome, "lib/security/jssecacerts"); if (!file.exists()) { file = new File(javaHome, "lib/security/cacerts"); trustStoreFile = file; } else { trustStoreFile = file; } trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); } final String password = System.getProperty("javax.net.ssl.trustStorePassword"); try (FileInputStream in = new FileInputStream(trustStoreFile)) { trustStore.load(in, password != null ? password.toCharArray() : null); } trustManagerFactory.init(trustStore); } return trustManagerFactory.getTrustManagers(); }
From source file:edu.vt.alerts.android.library.tasks.RegistrationTask.java
private KeyStore createKeyStore(KeyPair keyPair, HttpResponse response) throws Exception { Log.i("registration", "Got status from registration server: " + response.getStatusLine()); HttpEntity entity = response.getEntity(); byte[] contents = getBytes(entity.getContent()); Collection<?> certs = extractCerts(contents); Certificate[] certificates = new Certificate[certs.size()]; Log.i("registration", "Extracted out " + certs.size() + " certs"); CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); Iterator<?> it = certs.iterator(); int i = 0;// w w w .java2 s .c o m while (it.hasNext()) { byte[] encoded = ((X509CertificateHolder) it.next()).getEncoded(); certificates[i++] = (X509Certificate) certFactory .generateCertificate(new ByteArrayInputStream(encoded)); } Log.d("registration", "Creating local keystore"); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null); keyStore.setKeyEntry("Cert", keyPair.getPrivate(), "changeit".toCharArray(), certificates); return keyStore; }
From source file:org.alfresco.extension.pdftoolkit.repo.action.executer.PDFSignatureActionExecuter.java
/** * // w w w . j ava 2s. c om * @param ruleAction * @param actionedUponNodeRef * @param actionedUponContentReader */ protected void doSignature(Action ruleAction, NodeRef actionedUponNodeRef, ContentReader actionedUponContentReader) { NodeRef privateKey = (NodeRef) ruleAction.getParameterValue(PARAM_PRIVATE_KEY); String location = (String) ruleAction.getParameterValue(PARAM_LOCATION); String position = (String) ruleAction.getParameterValue(PARAM_POSITION); String reason = (String) ruleAction.getParameterValue(PARAM_REASON); String visibility = (String) ruleAction.getParameterValue(PARAM_VISIBILITY); String keyPassword = (String) ruleAction.getParameterValue(PARAM_KEY_PASSWORD); String keyType = (String) ruleAction.getParameterValue(PARAM_KEY_TYPE); int height = getInteger(ruleAction.getParameterValue(PARAM_HEIGHT)); int width = getInteger(ruleAction.getParameterValue(PARAM_WIDTH)); int pageNumber = getInteger(ruleAction.getParameterValue(PARAM_PAGE)); // New keystore parameters String alias = (String) ruleAction.getParameterValue(PARAM_ALIAS); String storePassword = (String) ruleAction.getParameterValue(PARAM_STORE_PASSWORD); int locationX = getInteger(ruleAction.getParameterValue(PARAM_LOCATION_X)); int locationY = getInteger(ruleAction.getParameterValue(PARAM_LOCATION_Y)); File tempDir = null; ContentWriter writer = null; KeyStore ks = null; try { // get a keystore instance by if (keyType == null || keyType.equalsIgnoreCase(KEY_TYPE_DEFAULT)) { ks = KeyStore.getInstance(KeyStore.getDefaultType()); } else if (keyType.equalsIgnoreCase(KEY_TYPE_PKCS12)) { ks = KeyStore.getInstance("pkcs12"); } else { throw new AlfrescoRuntimeException("Unknown key type " + keyType + " specified"); } // open the reader to the key and load it ContentReader keyReader = getReader(privateKey); ks.load(keyReader.getContentInputStream(), storePassword.toCharArray()); // set alias // String alias = (String) ks.aliases().nextElement(); PrivateKey key = (PrivateKey) ks.getKey(alias, keyPassword.toCharArray()); Certificate[] chain = ks.getCertificateChain(alias); // open original pdf ContentReader pdfReader = getReader(actionedUponNodeRef); PdfReader reader = new PdfReader(pdfReader.getContentInputStream()); // create temp dir to store file File alfTempDir = TempFileProvider.getTempDir(); tempDir = new File(alfTempDir.getPath() + File.separatorChar + actionedUponNodeRef.getId()); tempDir.mkdir(); File file = new File(tempDir, serviceRegistry.getFileFolderService().getFileInfo(actionedUponNodeRef).getName()); FileOutputStream fout = new FileOutputStream(file); PdfStamper stamp = PdfStamper.createSignature(reader, fout, '\0'); PdfSignatureAppearance sap = stamp.getSignatureAppearance(); sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED); // set reason for signature and location of signer sap.setReason(reason); sap.setLocation(location); if (visibility.equalsIgnoreCase(PDFSignatureActionExecuter.VISIBILITY_VISIBLE)) { //create the signature rectangle using either the provided position or //the exact coordinates, if provided if (position != null && !position.trim().equalsIgnoreCase("")) { Rectangle pageRect = reader.getPageSizeWithRotation(pageNumber); sap.setVisibleSignature(positionSignature(position, pageRect, width, height), pageNumber, null); } else { sap.setVisibleSignature( new Rectangle(locationX, locationY, locationX + width, locationY - height), pageNumber, null); } } stamp.close(); //can't use BasePDFActionExecuter.getWriter here need the nodeRef of the destination NodeRef destinationNode = createDestinationNode(file.getName(), (NodeRef) ruleAction.getParameterValue(PARAM_DESTINATION_FOLDER), actionedUponNodeRef); writer = serviceRegistry.getContentService().getWriter(destinationNode, ContentModel.PROP_CONTENT, true); writer.setEncoding(actionedUponContentReader.getEncoding()); writer.setMimetype(FILE_MIMETYPE); writer.putContent(file); file.delete(); //if useAspect is true, store some additional info about the signature in the props if (useAspect) { serviceRegistry.getNodeService().addAspect(destinationNode, PDFToolkitModel.ASPECT_SIGNED, new HashMap<QName, Serializable>()); serviceRegistry.getNodeService().setProperty(destinationNode, PDFToolkitModel.PROP_REASON, reason); serviceRegistry.getNodeService().setProperty(destinationNode, PDFToolkitModel.PROP_LOCATION, location); serviceRegistry.getNodeService().setProperty(destinationNode, PDFToolkitModel.PROP_SIGNATUREDATE, new java.util.Date()); serviceRegistry.getNodeService().setProperty(destinationNode, PDFToolkitModel.PROP_SIGNEDBY, AuthenticationUtil.getRunAsUser()); } } catch (IOException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (KeyStoreException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (ContentIOException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (NoSuchAlgorithmException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (CertificateException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (UnrecoverableKeyException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (DocumentException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } finally { if (tempDir != null) { try { tempDir.delete(); } catch (Exception ex) { throw new AlfrescoRuntimeException(ex.getMessage(), ex); } } } }
From source file:org.apache.nifi.web.security.x509.ocsp.OcspCertificateValidator.java
/** * Loads the trusted certificate authorities according to the specified properties. * * @param properties properties//from w w w . j a v a 2 s . c om * @return map of certificate authorities */ private Map<String, X509Certificate> getTrustedCAs(final NiFiProperties properties) { final Map<String, X509Certificate> certificateAuthorities = new HashMap<>(); // get the path to the truststore final String truststorePath = properties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE); if (truststorePath == null) { throw new IllegalArgumentException("The truststore path is required."); } // get the truststore password final char[] truststorePassword; final String rawTruststorePassword = properties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_PASSWD); if (rawTruststorePassword == null) { truststorePassword = new char[0]; } else { truststorePassword = rawTruststorePassword.toCharArray(); } // load the configured truststore try (final FileInputStream fis = new FileInputStream(truststorePath)) { final KeyStore truststore = KeyStoreUtils.getTrustStore(KeyStore.getDefaultType()); truststore.load(fis, truststorePassword); TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(truststore); // consider any certificates in the truststore as a trusted ca for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) { if (trustManager instanceof X509TrustManager) { for (X509Certificate ca : ((X509TrustManager) trustManager).getAcceptedIssuers()) { certificateAuthorities.put(ca.getSubjectX500Principal().getName(), ca); } } } } catch (final Exception e) { throw new IllegalStateException("Unable to load the configured truststore: " + e); } return certificateAuthorities; }