List of usage examples for java.security KeyStore setCertificateEntry
public final void setCertificateEntry(String alias, Certificate cert) throws KeyStoreException
From source file:org.votingsystem.util.HttpHelper.java
private HttpHelper() { try {//from w ww . j av a 2s . c o m KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLContext sslcontext = null; SSLConnectionSocketFactory sslsf = null; if (ContextVS.getInstance().getVotingSystemSSLCerts() != null) { log.info("loading SSLContext with app certificates"); X509Certificate sslServerCert = ContextVS.getInstance().getVotingSystemSSLCerts().iterator().next(); trustStore.setCertificateEntry(sslServerCert.getSubjectDN().toString(), sslServerCert); sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore).build(); X509HostnameVerifier hostnameVerifier = (X509HostnameVerifier) new AllowAllHostnameVerifier(); sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, hostnameVerifier); } else { sslcontext = SSLContexts.createSystemDefault(); sslsf = new SSLConnectionSocketFactory(sslcontext); log.info("loading default SSLContext"); } // Create a registry of custom connection socket factories for supported protocol schemes. Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder .<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE) .register("https", sslsf).build(); //Create socket configuration //SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).build(); //Configure the connection manager to use socket configuration either by default or for a specific host. //connManager.setDefaultSocketConfig(socketConfig); connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry, connFactory, dnsResolver); connManager.setMaxTotal(200); connManager.setDefaultMaxPerRoute(100); connEvictor = new IdleConnectionEvictor(connManager); connEvictor.start(); HttpRoute httpRouteVS = new HttpRoute(new HttpHost("www.sistemavotacion.org", 80)); connManager.setMaxPerRoute(httpRouteVS, 200); /* timeouts with large simulations -> RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(REQUEST_TIME_OUT) .setConnectionRequestTimeout(REQUEST_TIME_OUT).setSocketTimeout(REQUEST_TIME_OUT).build(); httpClient = HttpClients.custom().setConnectionManager(connManager).setDefaultRequestConfig( requestConfig).build();*/ httpClient = HttpClients.custom().setConnectionManager(connManager).build(); } catch (Exception ex) { log.log(Level.SEVERE, ex.getMessage(), ex); } }
From source file:mitm.djigzo.web.pages.certificate.CertificateImportKey.java
private void importPfx() throws KeyStoreException, NoSuchProviderException, SecurityFactoryFactoryException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableEntryException, WebServiceCheckedException {/* w w w . ja va 2 s . co m*/ /* * To prevent timeouts on the SOAP connection we should upload the PFX file in batches if the PFX file * contains a large number of entries. The PFX file should therefore be opened. */ KeyStore allKeys = SecurityFactoryFactory.getSecurityFactory().createKeyStore("PKCS12"); if (password == null) { password = ""; } allKeys.load(file.getStream(), password.toCharArray()); KeyAndCertificateWorkflow.MissingKey missingKey = ignoreMissingKey ? KeyAndCertificateWorkflow.MissingKey.SKIP_CERTIFICATE : KeyAndCertificateWorkflow.MissingKey.ADD_CERTIFICATE; int imported = 0; KeyStore batchKeys = SecurityFactoryFactory.getSecurityFactory().createKeyStore("PKCS12"); batchKeys.load(null, password.toCharArray()); Enumeration<String> aliases = allKeys.aliases(); KeyStore.PasswordProtection passwordProtection = new KeyStore.PasswordProtection(password.toCharArray()); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); if (allKeys.isKeyEntry(alias)) { KeyStore.Entry entry = allKeys.getEntry(alias, passwordProtection); batchKeys.setEntry(alias, entry, passwordProtection); } else { Certificate certificate = allKeys.getCertificate(alias); batchKeys.setCertificateEntry(alias, certificate); } if (batchKeys.size() >= maxBatchSize) { imported += uploadKeyStore(batchKeys, missingKey, password); batchKeys = SecurityFactoryFactory.getSecurityFactory().createKeyStore("PKCS12"); batchKeys.load(null, password.toCharArray()); } } /* * Check if there are still some entries left to add (happens when the number * of entries is not a multiple of maxBatchSize) */ if (batchKeys.size() > 0) { imported += uploadKeyStore(batchKeys, missingKey, password); } this.importCount = imported; }
From source file:de.stklcode.jvault.connector.HTTPVaultConnector.java
/** * Create a custom socket factory from trusted CA certificate. * * @return The factory./*from w w w . ja v a2 s . com*/ * @throws TlsException An error occured during initialization of the SSL context. * @since 0.8.0 */ private SSLConnectionSocketFactory createSSLSocketFactory() throws TlsException { try { // Create Keystore with trusted certificate. KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null); keyStore.setCertificateEntry("trustedCert", trustedCaCert); // Initialize TrustManager. TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(keyStore); // Create context usint this TrustManager. SSLContext context = SSLContext.getInstance(tlsVersion); context.init(null, tmf.getTrustManagers(), new SecureRandom()); return new SSLConnectionSocketFactory(context, null, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); } catch (CertificateException | NoSuchAlgorithmException | KeyStoreException | IOException | KeyManagementException e) { throw new TlsException(Error.INIT_SSL_CONTEXT, e); } }
From source file:org.nuxeo.ecm.platform.signature.core.pki.CertServiceImpl.java
@Override public KeyStore initializeUser(UserInfo userInfo, String suppliedPassword) throws CertException { char[] password = suppliedPassword.toCharArray(); KeyStore ks = null; String userName = userInfo.getUserFields().get(CNField.UserID); AliasWrapper keystoreAlias = new AliasWrapper(userName); try {/*from w w w.j a v a 2 s . c o m*/ ks = java.security.KeyStore.getInstance(KEYSTORE_TYPE); ks.load(null, password); KeyPairGenerator keyGen = KeyPairGenerator.getInstance(KEY_ALGORITHM); keyGen.initialize(KEY_SIZE); KeyPair keyPair = keyGen.genKeyPair(); java.security.cert.Certificate[] chain = { getRootCertificate() }; ks.setKeyEntry(keystoreAlias.getId(AliasType.KEY), keyPair.getPrivate(), password, chain); X509Certificate cert = getCertificate(keyPair, userInfo); ks.setCertificateEntry(keystoreAlias.getId(AliasType.CERT), cert); } catch (CertificateException e) { throw new CertException(e); } catch (IOException e) { throw new CertException(e); } catch (KeyStoreException e) { throw new CertException(e); } catch (NoSuchAlgorithmException e) { throw new CertException(e); } return ks; }
From source file:se.leap.bitmaskclient.ProviderAPI.java
private javax.net.ssl.SSLSocketFactory getProviderSSLSocketFactory() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, KeyManagementException { String provider_cert_string = preferences.getString(Provider.CA_CERT, ""); java.security.cert.Certificate provider_certificate = ConfigHelper .parseX509CertificateFromString(provider_cert_string); // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null);//from w w w . j a v a2s . c o m keyStore.setCertificateEntry("provider_ca_certificate", provider_certificate); // 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 context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); return context.getSocketFactory(); }
From source file:org.objectweb.proactive.extensions.ssl.KeyStoreCreator.java
private boolean update(String keyStore) { // Load the keystore FileInputStream fis = null;// www .ja va 2 s . c om try { fis = new FileInputStream(keyStore); } catch (FileNotFoundException e) { System.err.println("Failed to open the key store: " + e); return false; } KeyStore ks = null; try { ks = KeyStore.getInstance("PKCS12", SslHelpers.BC_NAME); ks.load(fis, SslHelpers.DEFAULT_KS_PASSWD.toCharArray()); } catch (Exception e) { System.err.println("Failed to open the key store: " + e); return false; } try { // Create a certificate CertificateGenerator gen = new CertificateGenerator(); KeyPair pair = gen.generateRSAKeyPair(); X509Certificate cert = gen.generateCertificate(SslHelpers.DEFAULT_SUBJET_DN, pair); // Remove the old certificate if needed try { ks.deleteEntry(SslHelpers.DEFAULT_SUBJET_DN); } catch (KeyStoreException e) { // OK } // Add the certificate ks.setCertificateEntry(SslHelpers.DEFAULT_SUBJET_DN, cert); // Write the keystore FileOutputStream fos = new FileOutputStream(new File(keyStore)); ks.store(fos, SslHelpers.DEFAULT_KS_PASSWD.toCharArray()); fos.close(); return true; } catch (Exception e) { System.err.println("Failed to update the keystore " + keyStore + ": " + e); return false; } }
From source file:org.apache.hadoop.yarn.server.resourcemanager.security.X509SecurityHandler.java
@InterfaceAudience.Private @VisibleForTesting//from w w w .j a v a 2s . c o m protected KeyStoresWrapper createApplicationStores(CertificateBundle certificateBundle, PrivateKey privateKey, String appUser, ApplicationId appId) throws GeneralSecurityException, IOException { char[] password = generateRandomPassword(); KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(null, null); X509Certificate[] chain = new X509Certificate[2]; chain[0] = certificateBundle.certificate; chain[1] = certificateBundle.issuer; keyStore.setKeyEntry(appUser, privateKey, password, chain); KeyStore systemTrustStore = loadSystemTrustStore(config); KeyStore appTrustStore = KeyStore.getInstance("JKS"); appTrustStore.load(null, null); Enumeration<String> aliases = systemTrustStore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); X509Certificate cert = (X509Certificate) systemTrustStore.getCertificate(alias); appTrustStore.setCertificateEntry(alias, cert); } return new KeyStoresWrapper(keyStore, password, appTrustStore, password, appUser, appId); }
From source file:org.lockss.util.KeyStoreUtil.java
private static void initializeKeyStore(KeyStore keyStore, Configuration config) throws CertificateException, IOException, InvalidKeyException, KeyStoreException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException, UnrecoverableKeyException { String keyAlias = config.get(PROP_KEY_ALIAS, DEFAULT_KEY_ALIAS); String certAlias = config.get(PROP_CERT_ALIAS, DEFAULT_CERT_ALIAS); String keyAlgName = config.get(PROP_KEY_ALGORITHM, DEFAULT_KEY_ALGORITHM); String sigAlgName = config.get(PROP_SIG_ALGORITHM, DEFAULT_SIG_ALGORITHM); String keyStorePassword = config.get(PROP_KEYSTORE_PASSWORD); String keyPassword = config.get(PROP_KEY_PASSWORD); int keyBits = config.getInt(PROP_KEY_BITS, DEFAULT_KEY_BITS); long expireIn = config.getTimeInterval(PROP_EXPIRE_IN, DEFAULT_EXPIRE_IN); String x500String = config.get(PROP_X500_NAME, DEFAULT_X500_NAME); CertAndKeyGen keypair = new CertAndKeyGen(keyAlgName, sigAlgName); keypair.generate(keyBits);/*from w w w . jav a2 s. c om*/ PrivateKey privKey = keypair.getPrivateKey(); log.debug3("PrivKey: " + privKey.getAlgorithm() + " " + privKey.getFormat()); X509Certificate[] chain = new X509Certificate[1]; X500Name x500Name = new X500Name(x500String); chain[0] = keypair.getSelfCertificate(x500Name, expireIn); log.debug3("Certificate: " + chain[0].toString()); keyStore.load(null, keyStorePassword.toCharArray()); keyStore.setCertificateEntry(certAlias, chain[0]); keyStore.setKeyEntry(keyAlias, privKey, keyPassword.toCharArray(), chain); Key myKey = keyStore.getKey(keyAlias, keyPassword.toCharArray()); log.debug("MyKey: " + myKey.getAlgorithm() + " " + myKey.getFormat()); }
From source file:edu.washington.shibboleth.attribute.resolver.provider.dataConnector.RwsDataConnector.java
/** * This sets the trust managers that will be used for all TLS and SSL connections to the ldap. This method will * remove any cached results and initialize the connection manager. * /* ww w . j a v a 2s .co m*/ * @see #clearCache() * @see #setSslSocketFactory(SSLSocketFactory) * * @param tc <code>X509Credential</code> to create TrustManagers with */ public void setSslTrustManagers(X509Credential tc) { if (tc != null) { try { TrustManagerFactory tmf = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); keystore.load(null, null); for (X509Certificate c : tc.getEntityCertificateChain()) { keystore.setCertificateEntry("ldap_tls_trust_" + c.getSerialNumber(), c); } tmf.init(keystore); sslTrustManagers = tmf.getTrustManagers(); } catch (GeneralSecurityException e) { log.error("Error initializing trust managers", e); } catch (IOException e) { log.error("Error initializing trust managers", e); } } }
From source file:org.signserver.module.xades.signer.XAdESSignerUnitTest.java
@Test public void testProcessData_basicSigningXAdESFormT() throws Exception { LOG.info("testProcessData_basicSigningXAdESFormT"); XAdESSigner instance = new MockedXAdESSigner(tokenRSA); WorkerConfig config = new WorkerConfig(); config.setProperty("XADESFORM", "T"); config.setProperty("TSA_URL", "http://example.com/?test=5"); instance.init(4711, config, null, null); instance.setTimeStampTokenProviderImplementation(MockedTimeStampTokenProvider.class); // reset mock counters MockedTimeStampTokenProvider.reset(); RequestContext requestContext = new RequestContext(); requestContext.put(RequestContext.TRANSACTION_ID, "0000-100-1"); GenericSignRequest request = new GenericSignRequest(100, "<test100/>".getBytes("UTF-8")); GenericSignResponse response = (GenericSignResponse) instance.processData(request, requestContext); byte[] data = response.getProcessedData(); final String signedXml = new String(data); LOG.debug("signedXml: " + signedXml); // Validation: setup CertStore certStore = CertStore.getInstance("Collection", new CollectionCertStoreParameters(tokenRSA.getCertificateChain(ICryptoToken.PURPOSE_SIGN))); KeyStore trustAnchors = KeyStore.getInstance("JKS"); trustAnchors.load(null, "foo123".toCharArray()); trustAnchors.setCertificateEntry("cert", tokenRSA.getCertificate(ICryptoToken.PURPOSE_SIGN)); CertificateValidationProvider certValidator = new PKIXCertificateValidationProvider(trustAnchors, false, certStore);//from w ww . j av a 2 s .com XadesVerificationProfile p = new XadesVerificationProfile(certValidator) .withTimeStampTokenVerifier(new MockedTimeStampVerificationProvider()); XadesVerifier verifier = p.newVerifier(); // Validation: parse final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); final DocumentBuilder builder = factory.newDocumentBuilder(); final Document doc = builder.parse(new ByteArrayInputStream(data)); Element node = doc.getDocumentElement(); XAdESVerificationResult r = verifier.verify(node, new SignatureSpecificVerificationOptions()); LOG.debug("signature form: " + r.getSignatureForm().name()); assertEquals("T", r.getSignatureForm().name()); assertEquals("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", r.getSignatureAlgorithmUri()); // check that a time stamp token was requested assertTrue("Should request a time stamp token", MockedTimeStampTokenProvider.hasRequestedTimeStampToken()); // check that the time stamp token was verified assertTrue("Should try to verify timestamp", MockedTimeStampTokenProvider.hasPerformedTimeStampVerification()); }