Example usage for java.security KeyStore getDefaultType

List of usage examples for java.security KeyStore getDefaultType

Introduction

In this page you can find the example usage for java.security KeyStore getDefaultType.

Prototype

public static final String getDefaultType() 

Source Link

Document

Returns the default keystore type as specified by the keystore.type security property, or the string "jks" (acronym for "Java keystore" ) if no such property exists.

Usage

From source file:com.machinepublishers.jbrowserdriver.StreamConnectionClient.java

private static SSLContext sslContext() {
    final String property = SettingsManager.settings().ssl();
    if (property != null && !property.isEmpty() && !"null".equals(property)) {
        if ("trustanything".equals(property)) {
            try {
                return SSLContexts.custom().loadTrustMaterial(KeyStore.getInstance(KeyStore.getDefaultType()),
                        new TrustStrategy() {
                            public boolean isTrusted(X509Certificate[] chain, String authType)
                                    throws CertificateException {
                                return true;
                            }/* w  w  w .j a  v  a  2 s  . c om*/
                        }).build();
            } catch (Throwable t) {
                LogsServer.instance().exception(t);
            }
        } else {
            try {
                String location = property;
                location = location.equals("compatible")
                        ? "https://raw.githubusercontent.com/bagder/ca-bundle/master/ca-bundle.crt"
                        : location;
                File cachedPemFile = new File("./pemfile_cached");
                boolean remote = location.startsWith("https://") || location.startsWith("http://");
                if (remote && cachedPemFile.exists()
                        && (System.currentTimeMillis() - cachedPemFile.lastModified() < 48 * 60 * 60 * 1000)) {
                    location = cachedPemFile.getAbsolutePath();
                    remote = false;
                }
                String pemBlocks = null;
                if (remote) {
                    HttpURLConnection remotePemFile = (HttpURLConnection) StreamHandler
                            .defaultConnection(new URL(location));
                    remotePemFile.setRequestMethod("GET");
                    remotePemFile.connect();
                    pemBlocks = Util.toString(remotePemFile.getInputStream(), Util.charset(remotePemFile));
                    cachedPemFile.delete();
                    Files.write(Paths.get(cachedPemFile.getAbsolutePath()), pemBlocks.getBytes("utf-8"));
                } else {
                    pemBlocks = new String(Files.readAllBytes(Paths.get(new File(location).getAbsolutePath())),
                            "utf-8");
                }
                KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
                keyStore.load(null);
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                Matcher matcher = pemBlock.matcher(pemBlocks);
                boolean found = false;
                while (matcher.find()) {
                    String pemBlock = matcher.group(1).replaceAll("[\\n\\r]+", "");
                    ByteArrayInputStream byteStream = new ByteArrayInputStream(
                            Base64.getDecoder().decode(pemBlock));
                    java.security.cert.X509Certificate cert = (java.security.cert.X509Certificate) cf
                            .generateCertificate(byteStream);
                    String alias = cert.getSubjectX500Principal().getName("RFC2253");
                    if (alias != null && !keyStore.containsAlias(alias)) {
                        found = true;
                        keyStore.setCertificateEntry(alias, cert);
                    }
                }
                if (found) {
                    KeyManagerFactory keyManager = KeyManagerFactory
                            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
                    keyManager.init(keyStore, null);
                    TrustManagerFactory trustManager = TrustManagerFactory
                            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
                    trustManager.init(keyStore);
                    SSLContext context = SSLContext.getInstance("TLS");
                    context.init(keyManager.getKeyManagers(), trustManager.getTrustManagers(), null);
                    return context;
                }
            } catch (Throwable t) {
                LogsServer.instance().exception(t);
            }
        }
    }
    return SSLContexts.createSystemDefault();
}

From source file:org.eclipse.mylyn.internal.commons.net.PollingSslProtocolSocketFactory.java

public synchronized SSLSocketFactory getSocketFactory() throws IOException {
    if (socketFactory == null) {
        if (keyStoreFileName != null && keyStorePassword != null) {
            KeyManager[] keymanagers = null;
            try {
                if (keyStoreType == null) {
                    try {
                        keymanagers = openKeyStore(KeyStore.getDefaultType());
                    } catch (Exception e) {
                        keymanagers = openKeyStore("pkcs12"); //$NON-NLS-1$
                    }//from  w  ww  .jav  a  2  s  .  c o m
                } else {
                    keymanagers = openKeyStore(keyStoreType);
                }
            } catch (Exception cause) {
                IOException e = new SslCertificateException();
                e.initCause(cause);
                throw e;
            }

            try {
                SSLContext sslContext = SSLContext.getInstance("SSL"); //$NON-NLS-1$
                sslContext.init(keymanagers, new TrustManager[] { new TrustAllTrustManager() }, null);
                this.socketFactory = sslContext.getSocketFactory();
            } catch (Exception cause) {
                IOException e = new SslCertificateException();
                e.initCause(cause);
                throw e;
            }
        }
        throw new IOException("Could not initialize SSL context"); //$NON-NLS-1$
    }
    return socketFactory;
}

From source file:org.godotengine.godot.utils.HttpRequester.java

private HttpClient getNewHttpClient() {
    try {//from  www.j a  va  2 s.com
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new CustomSSLSocketFactory(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:lynxtools.async_download.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient.//  w  w  w  .  j  av a  2 s. com
 */
public AsyncHttpClient() {
    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, socketTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams,
            String.format("android-async-http/%s (http://loopj.com/android-async-http)", VERSION));

    SchemeRegistry schemeRegistry = new SchemeRegistry();

    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    if (AsyncWraper.getTrustAllCertificates()) {
        try {
            //accepting all certificates because fuck this.
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);

            SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

            schemeRegistry.register(new Scheme("https", sf, 443));
            System.out.println("accepting all certificates");
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    }

    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                request.addHeader(header, clientHeaderMap.get(header));
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(response.getEntity()));
                        break;
                    }
                }
            }
        }
    });

    httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES));

    threadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool();

    clientHeaderMap = new HashMap<String, String>();

}

From source file:com.jayway.restassured.config.SSLConfig.java

/**
 * Creates a new SSL Config instance with the following settings:
 * <ul>/*  ww w.j  av  a  2 s . c o m*/
 * <li>No keystore</li>
 * <li>No password</li>
 * <li>{@link java.security.KeyStore#getDefaultType()}</li>
 * <li>No explicit default port</li>
 * <li>No trust store</li>
 * <li>No SSLSocketFactory</li>
 * <li>{@link org.apache.http.conn.ssl.SSLSocketFactory#STRICT_HOSTNAME_VERIFIER} as {@link X509HostnameVerifier} implementation</li>
 * </ul>
 */
public SSLConfig() {
    this(null, null, KeyStore.getDefaultType(), UNDEFINED_PORT, null, STRICT_HOSTNAME_VERIFIER, null, false);
}

From source file:com.bluexml.side.Framework.alfresco.signature.repo.action.executer.PDFSignatureActionExecuter.java

/**
 * /*from   www.j  a v a 2 s  .  c  o m*/
 * @param ruleAction
 * @param actionedUponNodeRef
 * @param actionedUponContentReader
 * @throws Exception 
 */
protected void doSignature(Action ruleAction, NodeRef actionedUponNodeRef,
        ContentReader actionedUponContentReader) throws Exception {

    NodeRef privateKey = (NodeRef) ruleAction.getParameterValue(PARAM_PRIVATE_KEY);
    String location = (String) ruleAction.getParameterValue(PARAM_LOCATION);
    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);
    String signedName = (String) ruleAction.getParameterValue(PARAM_SIGNED_NAME);
    int height = Integer.parseInt((String) ruleAction.getParameterValue(PARAM_HEIGHT));
    int width = Integer.parseInt((String) ruleAction.getParameterValue(PARAM_WIDTH));

    // New keystore parameters
    String alias = (String) ruleAction.getParameterValue(PARAM_ALIAS);
    String storePassword = (String) ruleAction.getParameterValue(PARAM_STORE_PASSWORD);

    // Ugly and verbose, but fault-tolerant
    String locationXStr = (String) ruleAction.getParameterValue(PARAM_LOCATION_X);
    String locationYStr = (String) ruleAction.getParameterValue(PARAM_LOCATION_Y);
    int locationX = 0;
    int locationY = 0;
    try {
        locationX = locationXStr != null ? Integer.parseInt(locationXStr) : 0;
    } catch (NumberFormatException e) {
        locationX = 0;
    }
    try {
        locationY = locationXStr != null ? Integer.parseInt(locationYStr) : 0;
    } catch (NumberFormatException e) {
        locationY = 0;
    }

    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 Exception("Unknown key type " + keyType + " specified");
        }

        // open the reader to the key and load it
        ContentReader keyReader = serviceRegistry.getContentService().getReader(privateKey,
                ContentModel.PROP_CONTENT);
        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)) {
            sap.setVisibleSignature(new Rectangle(locationX + width, locationY - height, locationX, locationY),
                    1, null);
        }

        stamp.close();

        String[] splitedFilename = file.getName().split("\\.");
        String name = "-" + signedName + "." + splitedFilename[splitedFilename.length - 1];
        for (int i = splitedFilename.length - 2; i >= 0; i--) {
            if (name.equals("-" + signedName + "." + splitedFilename[splitedFilename.length - 1])) {
                name = splitedFilename[i] + name;
            } else {
                name = splitedFilename[i] + "." + name;
            }
        }

        writer = getWriter(name, (NodeRef) ruleAction.getParameterValue(PARAM_DESTINATION_FOLDER));
        writer.setEncoding(actionedUponContentReader.getEncoding());
        writer.setMimetype(FILE_MIMETYPE);
        writer.putContent(file);

        file.delete();
    } catch (Exception e) {
        throw e;
    } finally {
        if (tempDir != null) {
            try {
                tempDir.delete();
            } catch (Exception ex) {
            }
        }
    }
}

From source file:org.apache.cxf.fediz.integrationtests.HTTPTestUtils.java

public static String sendHttpGetForSAMLSSO(String url, String user, String password, int returnCodeIDP,
        int returnCodeRP, int idpPort) throws Exception {

    CloseableHttpClient httpClient = null;
    try {/*from w  w  w . java  2  s . c  o m*/
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope("localhost", idpPort),
                new UsernamePasswordCredentials(user, password));

        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        FileInputStream instream = new FileInputStream(new File("./target/test-classes/client.jks"));
        try {
            trustStore.load(instream, "clientpass".toCharArray());
        } finally {
            try {
                instream.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
        sslContextBuilder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy());
        sslContextBuilder.loadKeyMaterial(trustStore, "clientpass".toCharArray());

        SSLContext sslContext = sslContextBuilder.build();
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext);

        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
        httpClientBuilder.setSSLSocketFactory(sslSocketFactory);
        httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy());

        httpClient = httpClientBuilder.build();

        HttpGet httpget = new HttpGet(url);

        HttpResponse response = httpClient.execute(httpget);
        HttpEntity entity = response.getEntity();

        System.out.println(response.getStatusLine());
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        Assert.assertTrue("RP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: "
                + returnCodeRP + "]", returnCodeRP == response.getStatusLine().getStatusCode());

        return EntityUtils.toString(entity);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        if (httpClient != null) {
            httpClient.close();
        }
    }
}

From source file:SignatureInfos.java

private KeyStore getKeystore() throws KeyStoreException {
    try {/* w  ww  . j  a  va2s .c o  m*/
        final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        //InputStream is = this.getClass().getResourceAsStream("/key.keystore");      
        //ks.load(is, getKeystorePassword().toCharArray());
        ks.load(new FileInputStream(getKeystoreFile()), getKeystorePassword().toCharArray());
        return ks;
    } catch (final NoSuchAlgorithmException e) {
        throw new KeyStoreException(e);
    } catch (final CertificateException e) {
        throw new KeyStoreException(e);
    } catch (final FileNotFoundException e) {
        throw new KeyStoreException(e);
    } catch (final IOException e) {
        throw new KeyStoreException(e);
    }
}

From source file:at.gv.egovernment.moa.id.configuration.config.ConfigurationProvider.java

public KeyStore getPVP2KeyStore() throws ConfigurationException, IOException, NoSuchAlgorithmException,
        CertificateException, KeyStoreException {
    if (keyStore == null) {
        String keystoretype = getPVP2MetadataKeystoreType();
        if (MiscUtil.isEmpty(keystoretype)) {
            log.debug("No KeyStoreType defined. Using default KeyStoreType.");
            keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

        } else {//from   ww  w  .j a va 2s. c  o m
            log.debug("Using " + keystoretype + " KeyStoreType.");
            keyStore = KeyStore.getInstance(keystoretype);

        }

        String fileURL = getPVP2MetadataKeystoreURL();
        log.debug("Load KeyStore from URL " + fileURL);
        if (MiscUtil.isEmpty(fileURL)) {
            log.info("Metadata KeyStoreURL is empty");
            throw new ConfigurationException("Metadata KeyStoreURL is empty");
        }

        URL keystoreURL = new URL((FileUtils.makeAbsoluteURL(fileURL, getConfigRootDir())));
        InputStream inputStream = keystoreURL.openStream();
        keyStore.load(inputStream, getPVP2MetadataKeystorePassword().toCharArray());
        inputStream.close();
    }

    return keyStore;

}

From source file:org.seedstack.seed.crypto.internal.EncryptionServiceFactoryTest.java

/**
 * Test method for/*from w ww .  j ava  2 s  .co m*/
 * {@link org.seedstack.seed.crypto.internal.EncryptionServiceFactory#createEncryptionService(org.seedstack.seed.crypto.internal.KeyStoreDefinition, org.seedstack.seed.crypto.internal.CertificateDefinition)}
 * . Test a {@link FileNotFoundException} if no keystore found.
 *
 * @throws Exception if an error occurred
 */
@Test(expected = RuntimeException.class)
public void testCreateEncryptionServiceWithNoKeystoreFound(@Mocked final KeyStoreDefinition keyStoreDefinition,
        @Mocked final CertificateDefinition certificateDefinition, @Mocked final KeyStore keyStore,
        @SuppressWarnings("unused") @Mocked final FileInputStream file) throws Exception {
    new Expectations() {
        final String pathToKeystore = "pathToKeystore";

        {
            keyStoreDefinition.getPath();
            returns(pathToKeystore);

            KeyStore.getInstance(KeyStore.getDefaultType());
            returns(keyStore);

            new FileInputStream(pathToKeystore);
            result = new FileNotFoundException("dummy exception");
        }
    };

    EncryptionServiceFactory factory = new EncryptionServiceFactory();
    factory.createEncryptionService(keyStoreDefinition, certificateDefinition);

}