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:eu.europa.esig.dss.token.JKSSignatureToken.java

/**
 * Creates a SignatureTokenConnection with the provided InputStream to Java KeyStore file and password.
 *
 * @param ksStream//www .  j  a  v a  2s .co  m
 * @param ksPassword
 */
public JKSSignatureToken(InputStream ksStream, String ksPassword) {
    try {
        keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        password = (ksPassword == null) ? null : ksPassword.toCharArray();
        keyStore.load(ksStream, password);
    } catch (Exception e) {
        throw new DSSException(e);
    } finally {
        IOUtils.closeQuietly(ksStream);
    }
}

From source file:org.jwebsocket.sso.HTTPSupport.java

/**
 *
 * @param aURL//w  w  w .  jav  a2 s .c o  m
 * @param aMethod
 * @param aHeaders
 * @param aPostBody
 * @param aTimeout
 * @return
 */
public static String request(String aURL, String aMethod, Map<String, String> aHeaders, String aPostBody,
        long aTimeout) {
    if (mLog.isDebugEnabled()) {
        mLog.debug("Requesting (" + aMethod + ") '" + aURL + "', timeout: " + aTimeout + "ms, Headers: "
                + aHeaders + ", Body: "
                + (null != aPostBody ? "'" + aPostBody.replace("\n", "\\n").replace("\r", "\\r") + "'"
                        : "[null]"));
    }
    String lResponse = "{\"code\": -1, \"msg\": \"undefined\"";
    try {
        KeyStore lTrustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        lTrustStore.load(null, null);
        // Trust own CA and all self-signed certs
        SSLContext lSSLContext = SSLContexts.custom()
                .loadTrustMaterial(lTrustStore, new TrustSelfSignedStrategy()).build();
        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory lSSLFactory = new SSLConnectionSocketFactory(lSSLContext,
                new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        CloseableHttpClient lHTTPClient = HttpClients.custom().setSSLSocketFactory(lSSLFactory).build();
        HttpUriRequest lRequest;
        if ("POST".equals(aMethod)) {
            lRequest = new HttpPost(aURL);
            ((HttpPost) lRequest).setEntity(new ByteArrayEntity(aPostBody.getBytes("UTF-8")));
        } else {
            lRequest = new HttpGet(aURL);
        }
        for (Map.Entry<String, String> lEntry : aHeaders.entrySet()) {
            lRequest.setHeader(lEntry.getKey(), lEntry.getValue());
        }

        // System.out.println("Executing request " + lRequest.getRequestLine());
        // Create a custom response handler
        ResponseHandler<String> lResponseHandler = new ResponseHandler<String>() {

            @Override
            public String handleResponse(final HttpResponse lResponse)
                    throws ClientProtocolException, IOException {
                int lStatus = lResponse.getStatusLine().getStatusCode();
                HttpEntity lEntity = lResponse.getEntity();
                return lEntity != null ? EntityUtils.toString(lEntity) : null;

                //               if (lStatus >= 200 && lStatus < 300) {
                //                  HttpEntity entity = lResponse.getEntity();
                //                  return entity != null ? EntityUtils.toString(entity) : null;
                //               } else {
                //                  throw new ClientProtocolException("Unexpected response status: " + lStatus);
                //               }
            }

        };
        long lStartedAt = System.currentTimeMillis();
        lResponse = lHTTPClient.execute(lRequest, lResponseHandler);
        if (mLog.isDebugEnabled()) {
            mLog.debug("Response (" + (System.currentTimeMillis() - lStartedAt) + "ms): '"
                    + lResponse.replace("\n", "\\n").replace("\r", "\\r") + "'");
        }
        return lResponse;
    } catch (Exception lEx) {
        String lMsg = "{\"code\": -1, \"msg\": \"" + lEx.getClass().getSimpleName() + " at http request: "
                + lEx.getMessage() + "\"}";
        mLog.error(lEx.getClass().getSimpleName() + ": " + lEx.getMessage() + ", returning: " + lMsg);
        lResponse = lMsg;
        return lResponse;
    }
}

From source file:ddf.security.common.util.CommonSSLFactory.java

/**
 * Creates a new SSLSocketFactory from a truststore and keystore. This is used during SSL
 * communication.//from w  w w. j  a  v  a2  s .c o  m
 * 
 * @param trustStoreLoc
 *            File path to the truststore.
 * @param trustStorePass
 *            Password to the truststore.
 * @param keyStoreLoc
 *            File path to the keystore.
 * @param keyStorePass
 *            Password to the keystore.
 * @return new SSLSocketFactory instance containing the trust and key stores.
 * @throws IOException
 */
public static SSLSocketFactory createSocket(String trustStoreLoc, String trustStorePass, String keyStoreLoc,
        String keyStorePass) throws IOException {
    String methodName = "createSocket";
    logger.debug("ENTERING: " + methodName);

    try {
        logger.debug("trustStoreLoc = " + trustStoreLoc);
        FileInputStream trustFIS = new FileInputStream(trustStoreLoc);
        logger.debug("keyStoreLoc = " + keyStoreLoc);
        FileInputStream keyFIS = new FileInputStream(keyStoreLoc);

        // truststore stuff
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        try {
            logger.debug("Loading trustStore");
            trustStore.load(trustFIS, trustStorePass.toCharArray());
        } catch (CertificateException e) {
            throw new IOException("Unable to load certificates from truststore. " + trustStoreLoc, e);
        } finally {
            IOUtils.closeQuietly(trustFIS);
        }

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trustStore);
        logger.debug("trust manager factory initialized");

        // keystore stuff
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        try {
            logger.debug("Loading keyStore");
            keyStore.load(keyFIS, keyStorePass.toCharArray());
        } catch (CertificateException e) {
            throw new IOException("Unable to load certificates from keystore. " + keyStoreLoc, e);
        } finally {
            IOUtils.closeQuietly(keyFIS);
        }
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(keyStore, keyStorePass.toCharArray());
        logger.debug("key manager factory initialized");

        // ssl context
        SSLContext sslCtx = SSLContext.getInstance("TLS");
        sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        sslCtx.getDefaultSSLParameters().setNeedClientAuth(true);
        sslCtx.getDefaultSSLParameters().setWantClientAuth(true);
        logger.debug(exiting + methodName);

        return sslCtx.getSocketFactory();
    } catch (KeyManagementException e) {
        logger.debug(exiting + methodName);
        throw new IOException("Unable to initialize the SSL context.", e);
    } catch (NoSuchAlgorithmException e) {
        logger.debug(exiting + methodName);
        throw new IOException(
                "Problems creating SSL socket. Usually this is "
                        + "referring to the certificate sent by the server not being trusted by the client.",
                e);
    } catch (UnrecoverableKeyException e) {
        logger.debug(exiting + methodName);
        throw new IOException("Unable to load keystore. " + keyStoreLoc, e);
    } catch (KeyStoreException e) {
        logger.debug(exiting + methodName);
        throw new IOException("Unable to read keystore. " + keyStoreLoc, e);
    }
}

From source file:com.navnorth.learningregistry.LRClient.java

public static HttpClient getHttpClient(String scheme) {

    // TODO: this allows for self-signed certificates, which should just be an option, not used by default.
    if (scheme.equals("https")) {
        try {/*from w  w w.  j  a v a2s .c  o  m*/
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);
            SSLSocketFactory sf = new SelfSignSSLSocketFactory(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();
        }
    } else {
        return new DefaultHttpClient();
    }
}

From source file:eu.europa.esig.dss.cookbook.sources.JavaKeyStoreTool.java

public JavaKeyStoreTool(final String ksUrlLocation, final String ksPassword) {

    InputStream ksStream = null;// w ww.  ja  v  a  2  s  .  c o m
    try {
        final URL ksLocation = new URL(ksUrlLocation);
        ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ksStream = ksLocation.openStream();
        ks.load(ksStream, (ksPassword == null) ? null : ksPassword.toCharArray());
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(ksStream);
    }
}

From source file:cn.keke.travelmix.EasySSLSocketFactory.java

private static KeyStore getEasyTrustStore()
        throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException {
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    trustStore.load(null, null);/*from   w ww  .jav  a  2s  . c  o  m*/
    return trustStore;
}

From source file:org.ulyssis.ipp.publisher.HttpOutput.java

private SSLContext createSslCustomContext() {
    try {//from  ww w .  ja v a  2 s .  c  o  m
        SSLContextBuilder builder = SSLContexts.custom();
        if (options.getKeystore().isPresent()) {
            KeyStore cks = KeyStore.getInstance(KeyStore.getDefaultType());
            cks.load(new FileInputStream(options.getKeystore().get().toFile()),
                    options.getKeystorePass().toCharArray());
            builder.loadKeyMaterial(cks, options.getKeystorePass().toCharArray());
        }

        if (options.getTruststore().isPresent()) {
            KeyStore tks = KeyStore.getInstance(KeyStore.getDefaultType());
            tks.load(new FileInputStream(options.getTruststore().get().toFile()),
                    options.getTruststorePass().toCharArray());
            builder.loadTrustMaterial(tks, new TrustSelfSignedStrategy());
        }

        if (!options.getKeystore().isPresent() && !options.getKeystore().isPresent()) {
            return SSLContext.getDefault();
        }

        return builder.build();
    } catch (Exception e) {
        // TODO: DO SOMETHING WITH THE EXCEPTION!
        LOG.error("Exception", e);
    }
    return null;
}

From source file:com.kixeye.chassis.transport.shared.JettyConnectorRegistry.java

/**
 * Register to listen to HTTPS./*from   www. jav  a 2  s  .c o  m*/
 * 
 * @param server
 * @param address
 * @throws Exception 
 */
public static void registerHttpsConnector(Server server, InetSocketAddress address, boolean selfSigned,
        boolean mutualSsl, String keyStorePath, String keyStoreData, String keyStorePassword,
        String keyManagerPassword, String trustStorePath, String trustStoreData, String trustStorePassword,
        String[] excludedCipherSuites) throws Exception {
    // SSL Context Factory
    SslContextFactory sslContextFactory = new SslContextFactory();

    if (selfSigned) {
        char[] passwordChars = UUID.randomUUID().toString().toCharArray();

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

        keyStore.load(null, passwordChars);

        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();

        v3CertGen.setSerialNumber(BigInteger.valueOf(new SecureRandom().nextInt()).abs());
        v3CertGen.setIssuerDN(new X509Principal("CN=" + "kixeye.com" + ", OU=None, O=None L=None, C=None"));
        v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30));
        v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)));
        v3CertGen.setSubjectDN(new X509Principal("CN=" + "kixeye.com" + ", OU=None, O=None L=None, C=None"));

        v3CertGen.setPublicKey(keyPair.getPublic());
        v3CertGen.setSignatureAlgorithm("MD5WithRSAEncryption");

        X509Certificate privateKeyCertificate = v3CertGen.generateX509Certificate(keyPair.getPrivate());

        keyStore.setKeyEntry("selfSigned", keyPair.getPrivate(), passwordChars,
                new java.security.cert.Certificate[] { privateKeyCertificate });

        ByteArrayOutputStream keyStoreBaos = new ByteArrayOutputStream();
        keyStore.store(keyStoreBaos, passwordChars);

        keyStoreData = new String(Hex.encode(keyStoreBaos.toByteArray()), Charsets.UTF_8);
        keyStorePassword = new String(passwordChars);
        keyManagerPassword = keyStorePassword;

        sslContextFactory.setTrustAll(true);
    }

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

    if (StringUtils.isNotBlank(keyStoreData)) {
        keyStore.load(new ByteArrayInputStream(Hex.decode(keyStoreData)), keyStorePassword.toCharArray());
    } else if (StringUtils.isNotBlank(keyStorePath)) {
        try (InputStream inputStream = new DefaultResourceLoader().getResource(keyStorePath).getInputStream()) {
            keyStore.load(inputStream, keyStorePassword.toCharArray());
        }
    }

    sslContextFactory.setKeyStore(keyStore);
    sslContextFactory.setKeyStorePassword(keyStorePassword);
    if (StringUtils.isBlank(keyManagerPassword)) {
        keyManagerPassword = keyStorePassword;
    }
    sslContextFactory.setKeyManagerPassword(keyManagerPassword);
    KeyStore trustStore = null;
    if (StringUtils.isNotBlank(trustStoreData)) {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(new ByteArrayInputStream(Hex.decode(trustStoreData)), trustStorePassword.toCharArray());
    } else if (StringUtils.isNotBlank(trustStorePath)) {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        try (InputStream inputStream = new DefaultResourceLoader().getResource(trustStorePath)
                .getInputStream()) {
            trustStore.load(inputStream, trustStorePassword.toCharArray());
        }
    }
    if (trustStore != null) {
        sslContextFactory.setTrustStore(trustStore);
        sslContextFactory.setTrustStorePassword(trustStorePassword);
    }
    sslContextFactory.setNeedClientAuth(mutualSsl);
    sslContextFactory.setExcludeCipherSuites(excludedCipherSuites);

    // SSL Connector
    ServerConnector connector = new ServerConnector(server,
            new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.toString()),
            new HttpConnectionFactory());
    connector.setHost(address.getHostName());
    connector.setPort(address.getPort());

    server.addConnector(connector);
}

From source file:org.openhealthtools.openatna.net.ConnectionCertificateHandler.java

/**
 * Creates a key/trust store and loads in the corresponding file.
 *//* w w w  . j ava2s.  c om*/
public static KeyStore createKeyStore(final URL url, final String password)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
    if (url == null) {
        throw new IllegalArgumentException("Keystore url may not be null");
    }
    log.debug("Initializing key store");
    KeyStore keystore = null;
    if (url.getFile().endsWith(".p12")) {
        keystore = KeyStore.getInstance("pkcs12");
    } else {
        keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    }
    keystore.load(url.openStream(), password != null ? password.toCharArray() : null);
    return keystore;
}

From source file:com.gmail.nagamatu.radiko.installer.MySSLSocketFactory.java

public static HttpClient getNewHttpClient() {
    try {/*w w  w.j  a v  a 2 s.  co m*/
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new MySSLSocketFactory(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();
    }
}