java.security.KeyStoreException Java Examples

The following examples show how to use java.security.KeyStoreException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CxfSecureRsExampleTest.java    From wildfly-camel-examples with Apache License 2.0 6 votes vote down vote up
private static void assertGreet(String uri, String user, String password, int responseCode,
        String responseBody) throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException,
        KeyStoreException, CertificateException, IOException {
    try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
        HttpGet request = new HttpGet(uri + "/Joe");
        request.setHeader("Content-Type", "application/json");
        if (user != null) {
            String auth = user + ":" + password;
            String authHeader = "Basic "
                    + Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.ISO_8859_1));
            request.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
        }
        try (CloseableHttpResponse response = httpclient.execute(request)) {
            final int actualCode = response.getStatusLine().getStatusCode();
            Assert.assertEquals(responseCode, actualCode);
            if (actualCode == 200) {
                HttpEntity entity = response.getEntity();
                String body = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                Assert.assertTrue(body.startsWith(responseBody));
            }
        }
    }
}
 
Example #2
Source File: CustomHttpClient.java    From zerocode-hello-world with MIT License 6 votes vote down vote up
/**
 * This method has been overridden here simply to show how a custom/project-specific http client
 * can be plugged into the framework.
 *
 * e.g. You can create your own project specific http client needed for http/https/tls connections or
 * a Corporate proxy based Http client here.
 * Sometimes you may need a simple default http client
 * e.g. HttpClients.createDefault() provided by Apache lib.
 *
 * Note:
 * If you do not override this method, the framework anyways creates a http client suitable for both http/https.
 */
@Override
public CloseableHttpClient createHttpClient() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {
    LOGGER.info("###Used SSL Enabled Http Client for http/https/TLS connections");

    SSLContext sslContext = new SSLContextBuilder()
            .loadTrustMaterial(null, (certificate, authType) -> true).build();

    CookieStore cookieStore = new BasicCookieStore();

    return HttpClients.custom()
            .setSSLContext(sslContext)
            .setSSLHostnameVerifier(new NoopHostnameVerifier())
            .setDefaultCookieStore(cookieStore)
            .build();
}
 
Example #3
Source File: BurpClientIT.java    From burp-rest-api with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testGetProxyHistoryAndSiteMap() throws IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
    HttpMessageList proxyHistory = burpClient.getProxyHistory();
    assertEquals(0, proxyHistory.getHttpMessages().size());

    String urlString = "http://www.vmware.com";

    HttpMessageList siteMap = burpClient.getSiteMap(urlString);
    assertEquals(0, siteMap.getHttpMessages().size());

    sendRequestThruProxy();

    proxyHistory = burpClient.getProxyHistory();
    assertNotEquals(0, proxyHistory.getHttpMessages().size());

    siteMap = burpClient.getSiteMap(urlString);
    assertNotEquals(0, siteMap.getHttpMessages().size());
}
 
Example #4
Source File: WebhookService.java    From webanno with Apache License 2.0 6 votes vote down vote up
public WebhookService()
    throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException
{
    TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain,
            String authType) -> true;

    SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
            .loadTrustMaterial(null, acceptingTrustStrategy).build();

    SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);

    CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();

    nonValidatingRequestFactory = new HttpComponentsClientHttpRequestFactory();
    nonValidatingRequestFactory.setHttpClient(httpClient);
}
 
Example #5
Source File: AbstractSpreadSheetDocumentRecordWriter.java    From hadoopoffice with Apache License 2.0 6 votes vote down vote up
/***
 * Reads the  (private) key and certificate from keystore to sign
 * 
 * @param conf
 * @throws OfficeWriterException
 * @throws IOException
 */
private void readSigningKeyAndCertificate(Configuration conf) throws OfficeWriterException, IOException {
	if ((this.howc.getSigKeystoreFile()!=null) && (!"".equals(this.howc.getSigKeystoreFile()))) {
		LOG.info("Signing document");
		if ((this.howc.getSigKeystoreAlias()==null) || ("".equals(this.howc.getSigKeystoreAlias()))) {
				LOG.error("Keystore alias for signature keystore not defined. Cannot sign document");
				throw new OfficeWriterException("Keystore alias for signature keystore not defined. Cannot sign document");
		}
		if ((this.howc.getSigKeystoreType()==null) || ("".equals(this.howc.getSigKeystoreType()))) {
			LOG.error("Keystore type for signature keystore not defined. Cannot sign document");
			throw new OfficeWriterException("Keystore type for signature keystore not defined. Cannot sign document");
		}
		LOG.info("Reading keystore");
		HadoopKeyStoreManager hksm = new HadoopKeyStoreManager(conf);
		try {
			hksm.openKeyStore(new Path(this.howc.getSigKeystoreFile()), this.howc.getSigKeystoreType(), this.howc.getSigKeystorePassword());
			this.howc.setSigKey(hksm.getPrivateKey(this.howc.getSigKeystoreAlias(), this.howc.getSigKeystorePassword()));
			this.howc.setSigCertificate((X509Certificate) hksm.getCertificate(this.howc.getSigKeystoreAlias()));
		} catch (NoSuchAlgorithmException | CertificateException | KeyStoreException | IllegalArgumentException | UnrecoverableKeyException  e) {
			LOG.error("Cannopt read signing certificate. Exception: ",e);
			throw new OfficeWriterException("Cannot read keystore to obtain key and certificate for signing "+e);
		}
		
		
	}
}
 
Example #6
Source File: RabbitMQContainerTest.java    From testcontainers-java with MIT License 6 votes vote down vote up
private SSLContext createSslContext(String keystoreFile, String keystorePassword, String truststoreFile, String truststorePassword)
    throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException, KeyManagementException
{
    ClassLoader classLoader = getClass().getClassLoader();

    KeyStore ks = KeyStore.getInstance("PKCS12");
    ks.load(new FileInputStream(new File(classLoader.getResource(keystoreFile).getFile())), keystorePassword.toCharArray());
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    kmf.init(ks, "password".toCharArray());

    KeyStore trustStore = KeyStore.getInstance("PKCS12");
    trustStore.load(new FileInputStream(new File(classLoader.getResource(truststoreFile).getFile())), truststorePassword.toCharArray());
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
    tmf.init(trustStore);

    SSLContext c = SSLContext.getInstance("TLSv1.2");
    c.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    return c;
}
 
Example #7
Source File: PKCS12KeyStore.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Deletes the entry identified by the given alias from this keystore.
 *
 * @param alias the alias name
 *
 * @exception KeyStoreException if the entry cannot be removed.
 */
public synchronized void engineDeleteEntry(String alias)
    throws KeyStoreException
{
    if (debug != null) {
        debug.println("Removing entry at alias '" + alias + "'");
    }

    Entry entry = entries.get(alias.toLowerCase(Locale.ENGLISH));
    if (entry instanceof PrivateKeyEntry) {
        PrivateKeyEntry keyEntry = (PrivateKeyEntry) entry;
        if (keyEntry.chain != null) {
            certificateCount -= keyEntry.chain.length;
        }
        privateKeyCount--;
    } else if (entry instanceof CertEntry) {
        certificateCount--;
    } else if (entry instanceof SecretKeyEntry) {
        secretKeyCount--;
    }
    entries.remove(alias.toLowerCase(Locale.ENGLISH));
}
 
Example #8
Source File: PFSecurityUtilsOld.java    From PFLockScreen-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Load AndroidKeyStore.
 * @return true if keystore loaded successfully
 */
private KeyStore loadKeyStore() throws PFSecurityException {
    try {
        final KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
        keyStore.load(null);
        return keyStore;
    } catch (KeyStoreException
            | NoSuchAlgorithmException
            | CertificateException
            | IOException e) {
        e.printStackTrace();
        throw new PFSecurityException(
                "Can not load keystore:" + e.getMessage(),
                PFSecurityUtilsErrorCodes.ERROR_LOAD_KEY_STORE
        );
    }
}
 
Example #9
Source File: MetadataEmptyTest.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
private void runTest() throws IOException, KeyStoreException,
        NoSuchAlgorithmException, CertificateException,
        UnrecoverableKeyException {
    KeyStore ks = Utils.loadKeyStore(KEYSTORE_PATH,
            Utils.KeyStoreType.pkcs12, PASSWORD);
    Key key = ks.getKey(ALIAS, PASSWORD);
    Certificate cert = ks
            .getCertificate(ALIAS);
    KeyStore.Entry entry = new KeyStore.PrivateKeyEntry(
            (PrivateKey) key,
            new Certificate[]{cert});
    if (!entry.getAttributes().isEmpty()) {
        throw new RuntimeException("Entry's attributes set "
                + "must be empty");
    }
    out.println("Test Passed");
}
 
Example #10
Source File: ApacheCloudStackClient.java    From apache-cloudstack-java-client with Apache License 2.0 6 votes vote down vote up
/**
 * This method creates an insecure SSL factory that will trust on self signed certificates.
 * For that we use {@link TrustSelfSignedStrategy}.
 */
protected SSLConnectionSocketFactory createInsecureSslFactory() {
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(new TrustSelfSignedStrategy());
        SSLContext sc = builder.build();

        if (acceptAllKindsOfCertificates) {
            TrustManager[] trustAllCerts = new TrustManager[1];
            TrustManager tm = new TrustAllManager();
            trustAllCerts[0] = tm;
            sc.init(null, trustAllCerts, null);

            HostnameVerifier hostnameVerifier = createInsecureHostNameVerifier();
            return new SSLConnectionSocketFactory(sc, hostnameVerifier);
        }
        return new SSLConnectionSocketFactory(sc);
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        throw new ApacheCloudStackClientRuntimeException(e);
    }
}
 
Example #11
Source File: X509CertUtil.java    From portecle with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Check whether or not a trusted certificate in the supplied keystore matches the the supplied X.509 certificate.
 *
 * @return The alias of the matching certificate in the keystore or null if there is no match
 * @param cert The certificate
 * @param keyStore The keystore
 * @throws CryptoException If there is a problem establishing trust
 */
public static String matchCertificate(KeyStore keyStore, X509Certificate cert)
    throws CryptoException
{
	try
	{
		for (Enumeration<String> en = keyStore.aliases(); en.hasMoreElements();)
		{
			String sAlias = en.nextElement();
			if (keyStore.isCertificateEntry(sAlias))
			{
				X509Certificate compCert = X509CertUtil.convertCertificate(keyStore.getCertificate(sAlias));

				if (cert.equals(compCert))
				{
					return sAlias;
				}
			}
		}
		return null;
	}
	catch (KeyStoreException ex)
	{
		throw new CryptoException(RB.getString("NoMatchCertificate.exception.message"), ex);
	}
}
 
Example #12
Source File: X509KeySelectorTest.java    From development with Apache License 2.0 6 votes vote down vote up
@Test()
public void select_publicKey_exception() throws Exception {
    // given
    selector = spy(new X509KeySelector(keystore));
    KeyInfo keyinfo = mock(KeyInfo.class);
    ArrayList<XMLStructure> list = new ArrayList<XMLStructure>();
    X509Data x509Data = mock(X509Data.class);
    list.add(x509Data);
    doReturn(list).when(keyinfo).getContent();
    ArrayList<Object> x509DataContent = new ArrayList<Object>();
    x509DataContent.add(mock(X509Certificate.class));
    doReturn(x509DataContent).when(x509Data).getContent();
    doThrow(new KeyStoreException("key exception")).when(selector)
            .getPublicKeyFromKeystore(any(X509Certificate.class),
                    any(SignatureMethod.class));

    // when
    try {
        selector.select(keyinfo, null, null, null);
        fail();
    } catch (KeySelectorException e) {
        assertTrue(e.getCause().getMessage().contains("key exception"));
    }
}
 
Example #13
Source File: SignerParams.java    From Xpatch with Apache License 2.0 6 votes vote down vote up
private static Key getKeyStoreKey(KeyStore ks, String keyAlias, List<char[]> passwords)
        throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {
    UnrecoverableKeyException lastFailure = null;
    for (char[] password : passwords) {
        try {
            return ks.getKey(keyAlias, password);
        } catch (UnrecoverableKeyException e) {
            lastFailure = e;
        }
    }
    if (lastFailure == null) {
        throw new RuntimeException("No key passwords");
    } else {
        throw lastFailure;
    }
}
 
Example #14
Source File: KeyStoreResolver.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Constructor KeyStoreIterator
 *
 * @param keyStore
 */
public KeyStoreIterator(KeyStore keyStore) {
    try {
        this.keyStore = keyStore;
        this.aliases = this.keyStore.aliases();
    } catch (KeyStoreException ex) {
        // empty Enumeration
        this.aliases = new Enumeration<String>() {
            public boolean hasMoreElements() {
                return false;
            }
            public String nextElement() {
                return null;
            }
        };
    }
}
 
Example #15
Source File: KeyStore.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Sets the certificate chain for the keystore entry.
 */
void setCertificateChain(X509Certificate[] chain)
    throws CertificateException, KeyStoreException
{
    for (int i = 0; i < chain.length; i++) {
        byte[] encoding = chain[i].getEncoded();
        if (i == 0 && privateKey != null) {
            storeCertificate(getName(), alias, encoding,
                encoding.length, privateKey.getHCryptProvider(),
                privateKey.getHCryptKey());

        } else {
            storeCertificate(getName(), alias, encoding,
                encoding.length, 0L, 0L); // no private key to attach
        }
    }
    certChain = chain;
}
 
Example #16
Source File: KeyStoreHelperTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private SecretKey storeKeyIntoKeyStoreFile(final String keyPhrase)
        throws CertificateException, NoSuchAlgorithmException, IOException, KeyStoreException,
        InvalidKeyException, InvalidKeySpecException {
    final KeyStore keyStore = KeyStore.getInstance("JCEKS");
    keyStore.load(null, KEYSTORE_SERVER_PASSWORD.toCharArray());

    final SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DES");
    final SecretKey mySecretKey = secretKeyFactory.generateSecret(new DESKeySpec(keyPhrase.getBytes()));
    final KeyStore.SecretKeyEntry skEntry = new KeyStore.SecretKeyEntry(mySecretKey);
    keyStore.setEntry(KEY_ALIAS, skEntry, new KeyStore.PasswordProtection(KEY_PASSWORD.toCharArray()));

    try (FileOutputStream fos = new java.io.FileOutputStream(KEYSTORE_JCEKS_FILENAME, false)) {
        keyStore.store(fos, KEYSTORE_SERVER_PASSWORD.toCharArray());
    }
    return mySecretKey;
}
 
Example #17
Source File: ConnectorCommon.java    From nextcloud-java-api with GNU General Public License v3.0 6 votes vote down vote up
public static CloseableHttpAsyncClient getInstance(ServerConfig serverConfig)
	throws IOException{
	if (HTTPC_CLIENT == null) {
		if (serverConfig.isTrustAllCertificates()) {
			try {
				SSLContext sslContext = SSLContexts.custom()
					.loadTrustMaterial(null, TrustAllStrategy.INSTANCE).build();
				HTTPC_CLIENT = HttpAsyncClients.custom()
					.setSSLHostnameVerifier((NoopHostnameVerifier.INSTANCE))
					.setSSLContext(sslContext)
					.build();
			} catch (KeyManagementException | NoSuchAlgorithmException
					| KeyStoreException e) {
				throw new IOException(e);
			} 
			
		} else {
			HTTPC_CLIENT = HttpAsyncClients.createDefault();
		}
		
		HTTPC_CLIENT.start();
	}
	return HTTPC_CLIENT;
}
 
Example #18
Source File: SecurityUtils.java    From RISE-V2G with MIT License 6 votes vote down vote up
/**
 * Returns a standard keystore which holds the respective credentials (private key and certificate chain).
 * 
 * @param keyStoreIS The input stream of the keystore
 * @param keyStorePassword The password which protects the keystore
 * @param keyStoreType The type of the keystore, either "jks" or "pkcs12"
 * @return The respective keystore
 */
private static KeyStore getKeyStore(InputStream keyStoreIS, String keyStorePassword, String keyStoreType) {
	KeyStore keyStore = null;
	
	try {
		keyStore = KeyStore.getInstance(keyStoreType);
		keyStore.load(keyStoreIS, keyStorePassword.toCharArray());
		keyStoreIS.close();
		return keyStore;
	} catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | 
			IOException | NullPointerException e) {
		getLogger().error(e.getClass().getSimpleName() + " occurred while trying to load keystore", e);
	} 
	
	return null;
}
 
Example #19
Source File: GetHTTP.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private SSLContext createSSLContext(final SSLContextService service)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException {

    final SSLContextBuilder sslContextBuilder = new SSLContextBuilder();

    if (StringUtils.isNotBlank(service.getTrustStoreFile())) {
        final KeyStore truststore = KeyStoreUtils.getTrustStore(service.getTrustStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getTrustStoreFile()))) {
            truststore.load(in, service.getTrustStorePassword().toCharArray());
        }
        sslContextBuilder.loadTrustMaterial(truststore, new TrustSelfSignedStrategy());
    }

    if (StringUtils.isNotBlank(service.getKeyStoreFile())){
        final KeyStore keystore = KeyStoreUtils.getKeyStore(service.getKeyStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getKeyStoreFile()))) {
            keystore.load(in, service.getKeyStorePassword().toCharArray());
        }
        sslContextBuilder.loadKeyMaterial(keystore, service.getKeyStorePassword().toCharArray());
    }

    sslContextBuilder.useProtocol(service.getSslAlgorithm());

    return sslContextBuilder.build();
}
 
Example #20
Source File: Cryptography.java    From zap-android with MIT License 6 votes vote down vote up
private byte[] rsaEncryptKey(byte[] secret) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException, NoSuchProviderException, NoSuchPaddingException, UnrecoverableEntryException, InvalidKeyException {

        KeyStore keyStore = KeyStore.getInstance(ANDROID_KEY_STORE_NAME);
        keyStore.load(null);

        KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(KEY_ENCRYPTION, null);
        Cipher inputCipher = Cipher.getInstance(RSA_MODE, CIPHER_PROVIDER_NAME_ENCRYPTION_DECRYPTION_RSA);
        inputCipher.init(Cipher.ENCRYPT_MODE, privateKeyEntry.getCertificate().getPublicKey());

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, inputCipher);
        cipherOutputStream.write(secret);
        cipherOutputStream.close();

        byte[] encryptedKeyAsByteArray = outputStream.toByteArray();
        return encryptedKeyAsByteArray;
    }
 
Example #21
Source File: ReportServer.java    From dsworkbench with Apache License 2.0 6 votes vote down vote up
public void start(int pPort) throws IOException {
    if (sslWorkerThread == null) {
        //keystore including the key for HTTPs connection
        String ksName = "dsworkbench.jks";
        char ksPass[] = "dsworkbench".toCharArray();
        char ctPass[] = "dsworkbench".toCharArray();
        try {
            KeyStore ks = KeyStore.getInstance("JKS");
            ks.load(new FileInputStream(ksName), ksPass);
            KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
            kmf.init(ks, ctPass);
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(kmf.getKeyManagers(), null, null);
            SSLServerSocketFactory ssf = sc.getServerSocketFactory();
            SSLServerSocket s = (SSLServerSocket) ssf.createServerSocket(pPort);
            s.setEnabledCipherSuites(sc.getServerSocketFactory().getSupportedCipherSuites());
            sslWorkerThread = new SSLWorkerThread(s);
            sslWorkerThread.start();
        } catch (NoSuchAlgorithmException | CertificateException | KeyStoreException | KeyManagementException | UnrecoverableKeyException ex) {
            logger.error("Failed to decrypt SSL key.", ex);
        }
    } else {
        logger.info("Server is already running");
    }
}
 
Example #22
Source File: ClientKey.java    From eet-client with MIT License 5 votes vote down vote up
/**
  * Create new ClientKey instance based on data provided in the stream together with the password
  * @deprecated use
  * @param inputStream expects a stream to the pk12 keystore with one pair of key/cert. Will be closed automatically
  */
 public ClientKey(final InputStream inputStream, final String password) throws InvalidKeystoreException {

     if(inputStream == null) {
         throw new InvalidKeystoreException("Input stream of ClientKey cannot be NULL");
     }

     JavaCryptographyExtension.validateInstallation();

     this.password = password;
     String tempAlias = null;
     final KeyStore keystore = getKeyStore(inputStream, password);
     final Enumeration<String> aliases = getAliases(keystore);
     while (aliases.hasMoreElements()) {
         final String alias = aliases.nextElement();
         try {
	if (keystore.isKeyEntry(alias)) {
		tempAlias = alias;
                 String certificateInfo = CertificateUtils.getCertificateInfo(keystore, alias);
                 logger.info(certificateInfo);
                 CertExpirationChecker.of(keystore, alias)
                         .whenExpiresIn(30, TimeUnit.DAYS)
                         .printWarningTo(logger);
             }
} catch (final KeyStoreException e) {
	logger.error(String.format("cannot check isKeyEntry(%s) - %s : %s", alias, e.getClass().getName(), e.getMessage()));
}
     }
     if (tempAlias == null) {
         throw new InvalidKeystoreException("Keystore doesn't contain any keys!");
     }
     this.alias = tempAlias;
     this.keyStore = keystore;
     this.clientPasswordCallback = new ClientPasswordCallback(alias, password);
 }
 
Example #23
Source File: HttpClient.java    From TrackRay with GNU General Public License v3.0 5 votes vote down vote up
public CrawlerPage requestThrow(CrawlerPage crawlerPage) throws IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
    if (crawlerPage.getProxy()!=null && proxy == null)
        setProxy(crawlerPage.getProxy());
    HttpClientWrapper hw = new HttpClientWrapper(proxy);
    if (crawlerPage.getRequest().getUrl().toLowerCase().startsWith("https")) {
        enableSSL();
    }
    return hw.sendRequestThrow(crawlerPage);
}
 
Example #24
Source File: ElasticSearchClient.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
private boolean createClientDocker()
{
	CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
	credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("admin", "admin"));
	
	TrustStrategy trustStrategy = new TrustSelfSignedStrategy();
	SSLContext sslContext;
	try {
		sslContext = SSLContexts.custom().loadTrustMaterial(trustStrategy).build();
		HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
		
		RestClientBuilder restClientBuilder = createRestClientBuilder(hostname, scheme);
		
		restClientBuilder.setHttpClientConfigCallback(new HttpClientConfigCallback() {
			@Override
			public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
				httpClientBuilder.setSSLContext(sslContext).setSSLHostnameVerifier(hostnameVerifier).build();
				httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
				return httpClientBuilder;
			}
		});

		return createHighLevelClient(restClientBuilder);
	} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
		logger.error("Error while creating secure connection to ElasticSearch: ", e);
	}
	
	return false;
}
 
Example #25
Source File: CertificateLoaderImpl.java    From signer with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * When a PIN(Personal Identification Number) and Alias was informed, 
 * obtain the certificate from a Token or Smartcard, defined by ICP-BRASIL with the name A3.
 *
 * @param pinNumber a PIN(Personal Identification Number)
 * @param alias desired alias
 * @return  the certificate information in X509Certificate format
 * 
 */
 @Override
public X509Certificate loadFromToken(String pinNumber, String alias) {
    if (this.keyStore == null) {
        KeyStoreLoader keyStoreLoader = KeyStoreLoaderFactory.factoryKeyStoreLoader();
        this.keyStore = keyStoreLoader.getKeyStore();
    }
    try {
        return (X509Certificate) this.keyStore.getCertificateChain(alias)[0];
    } catch (KeyStoreException e) {
        throw new CertificateCoreException("", e);
    }
}
 
Example #26
Source File: DebugKeyProvider.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the debug {@link PrivateKey} to use to sign applications for debug purpose.
 * @return the private key or <code>null</code> if its creation failed.
 */
@SuppressWarnings("unused") // the thrown Exceptions are not actually thrown
public PrivateKey getDebugKey() throws KeyStoreException, NoSuchAlgorithmException,
        UnrecoverableKeyException, UnrecoverableEntryException {
    if (mEntry != null) {
        return mEntry.getPrivateKey();
    }

    return null;
}
 
Example #27
Source File: PrivateKeyResolver.java    From JDKSourceCode1.8 with MIT License 5 votes vote down vote up
private PrivateKey resolveX509SKI(XMLX509SKI x509SKI) throws XMLSecurityException, KeyStoreException {
    log.log(java.util.logging.Level.FINE, "Can I resolve X509SKI?");

    Enumeration<String> aliases = keyStore.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        if (keyStore.isKeyEntry(alias)) {

            Certificate cert = keyStore.getCertificate(alias);
            if (cert instanceof X509Certificate) {
                XMLX509SKI certSKI = new XMLX509SKI(x509SKI.getDocument(), (X509Certificate) cert);

                if (certSKI.equals(x509SKI)) {
                    log.log(java.util.logging.Level.FINE, "match !!! ");

                    try {
                        Key key = keyStore.getKey(alias, password);
                        if (key instanceof PrivateKey) {
                            return (PrivateKey) key;
                        }
                    } catch (Exception e) {
                        log.log(java.util.logging.Level.FINE, "Cannot recover the key", e);
                        // Keep searching
                    }
                }
            }
        }
    }

    return null;
}
 
Example #28
Source File: HTTPInvoker.java    From product-emm with Apache License 2.0 5 votes vote down vote up
private static HttpClient createHttpClient()
        throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    HttpClientBuilder b = HttpClientBuilder.create();

    // setup a Trust Strategy that allows all certificates.
    //
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
        public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            return true;
        }
    }).build();
    b.setSSLContext(sslContext);
    //b.setSSLHostnameVerifier(new NoopHostnameVerifier());

    // don't check Hostnames, either.
    //      -- use SSLConnectionSocketFactory.getDefaultHostnameVerifier(), if you don't want to weaken
    HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

    // here's the special part:
    //      -- need to create an SSL Socket Factory, to use our weakened "trust strategy";
    //      -- and create a Registry, to register it.
    //
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslSocketFactory)
            .build();

    // now, we create connection-manager using our Registry.
    //      -- allows multi-threaded use
    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    b.setConnectionManager(connMgr);

    // finally, build the HttpClient;
    //      -- done!
    CloseableHttpClient client = b.build();
    return client;
}
 
Example #29
Source File: DummyX509TrustManager.java    From anthelion with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor for DummyX509TrustManager.
 */
public DummyX509TrustManager(KeyStore keystore) throws NoSuchAlgorithmException, KeyStoreException {
    super();
    String algo = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory factory = TrustManagerFactory.getInstance(algo);
    factory.init(keystore);
    TrustManager[] trustmanagers = factory.getTrustManagers();
    if (trustmanagers.length == 0) {
        throw new NoSuchAlgorithmException(algo + " trust manager not supported");
    }
    this.standardTrustManager = (X509TrustManager)trustmanagers[0];
}
 
Example #30
Source File: SparkExceptionsTrustManager.java    From Spark with Apache License 2.0 5 votes vote down vote up
/**
 * Validate certificate path. As it is exception, no checks against revocation or time validity are done but path
 * still have to be validated in order to find connection between certificate presented by server and root CA in
 * KeyStore
 * 
 * @throws NoSuchAlgorithmException
 * @throws KeyStoreException
 * @throws InvalidAlgorithmParameterException
 * @throws CertPathValidatorException
 * @throws CertPathBuilderException
 * @throws CertificateException
 */
private void validatePath(X509Certificate[] chain)
        throws NoSuchAlgorithmException, KeyStoreException, InvalidAlgorithmParameterException,
        CertPathValidatorException, CertPathBuilderException, CertificateException {

    CertPathValidator certPathValidator = CertPathValidator.getInstance("PKIX");
    CertPathBuilder certPathBuilder = CertPathBuilder.getInstance("PKIX");
    X509CertSelector certSelector = new X509CertSelector();
    certSelector.setCertificate(chain[chain.length - 1]);
    // checks against time validity aren't done here as it exceptions list
    certSelector.setCertificateValid(null);
    PKIXBuilderParameters parameters = new PKIXBuilderParameters(allStore, certSelector);
    // no checks against revocation as it is exception
    parameters.setRevocationEnabled(false);

    CertPathBuilderResult pathResult = certPathBuilder.build(parameters);
    CertPath certPath = pathResult.getCertPath();
    PKIXCertPathValidatorResult validationResult = (PKIXCertPathValidatorResult) certPathValidator
            .validate(certPath, parameters);
    X509Certificate trustedCert = validationResult.getTrustAnchor().getTrustedCert();

    if (trustedCert == null) {
        throw new CertificateException("Certificate path failed");
    } else {
        Log.debug("ClientTrustManager: Trusted CA: " + trustedCert.getSubjectDN());
    }

}