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:org.comixwall.pffw.Utils.java

/**
 * Create an SSL context which trusts the PFFW server certificate.
 * PFFW server certificate is self signed, hence is not verified by the default SSL context.
 *
 * @param owner Fragment which initiated the call to this method.
 * @return SSL context.//from   w w w  .j  a  v a 2 s.com
 */
static SSLContext getSslContext(final Fragment owner) {
    SSLContext sslContext = null;
    try {
        // Load our crt from an InputStream
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        InputStream crtInput = owner.getResources().openRawResource(
                owner.getResources().getIdentifier("server", "raw", owner.getActivity().getPackageName()));

        Certificate crt;
        try {
            crt = cf.generateCertificate(crtInput);
            logger.finest("server.crt=" + ((X509Certificate) crt).getSubjectDN());
        } finally {
            crtInput.close();
        }

        // Create a KeyStore containing our trusted crt
        String keyStoreType = KeyStore.getDefaultType();
        KeyStore keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(null, null);
        keyStore.setCertificateEntry("server.crt", crt);

        // Create a TrustManager that trusts the crt in our KeyStore
        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(keyStore);

        // Create an SSLContext that uses our TrustManager
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, tmf.getTrustManagers(), null);

    } catch (Exception e) {
        e.printStackTrace();
        logger.severe("getSslContext exception: " + e.toString());
    }
    return sslContext;
}

From source file:HttpsRequestDemo.java

private void registerSSLSocketFactory(HttpClient httpclient) throws Exception {
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    // E:\\cer\\cpic_jttp.keystore
    FileInputStream instream = new FileInputStream(
            new File("E:\\Program Files\\Java\\jdk1.7.0_21\\bin\\cpic_jttp.keystore"));
    try {//from w ww . j ava  2s .c o  m
        trustStore.load(instream, "cpicJttp".toCharArray());
    } finally {
        instream.close();
    }

    SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
    Scheme sch = new Scheme("https", socketFactory, 443);
    httpclient.getConnectionManager().getSchemeRegistry().register(sch);
}

From source file:net.di2e.ecdr.security.ssl.client.cxf.CxfSSLClientConfigurationImpl.java

@Override
public void configurationUpdateCallback(Map<String, String> updatedConfiguration) {
    if (updatedConfiguration != null) {
        String keystore = updatedConfiguration.get(ConfigurationManager.KEY_STORE);
        String keystorePassword = updatedConfiguration.get(ConfigurationManager.KEY_STORE_PASSWORD);

        KeyManager[] keyManagers = null;
        if (StringUtils.isNotBlank(keystore) && keystorePassword != null) {
            try {
                KeyManager manager = KeyManagerUtils.createClientKeyManager(new File(keystore),
                        keystorePassword);
                keyManagers = new KeyManager[1];
                keyManagers[0] = manager;

            } catch (IOException | GeneralSecurityException ex) {
                LOGGER.debug("Could not access keystore {}, using default java keystore.", keystore);
            }//from  www .  ja v  a  2 s  . c o  m
        }

        String trustStoreLocation = updatedConfiguration.get(ConfigurationManager.TRUST_STORE);
        String trustStorePassword = updatedConfiguration.get(ConfigurationManager.TRUST_STORE_PASSWORD);
        TrustManager[] trustManagers = null;
        if (StringUtils.isNotBlank(trustStoreLocation) && trustStorePassword != null) {
            try (FileInputStream fis = new FileInputStream(trustStoreLocation)) {
                KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
                try {
                    trustStore.load(fis,
                            StringUtils.isNotEmpty(trustStorePassword) ? trustStorePassword.toCharArray()
                                    : null);
                    trustManagers = new TrustManager[1];
                    trustManagers[0] = TrustManagerUtils.getDefaultTrustManager(trustStore);
                } catch (IOException ioe) {
                    LOGGER.debug("Could not load truststore {}, using default java truststore");
                }
            } catch (IOException | GeneralSecurityException ex) {
                LOGGER.debug("Could not access truststore {}, using default java truststore.",
                        trustStoreLocation);
            }
        }
        synchronized (tlsClientParameters) {
            LOGGER.debug(
                    "Setting the CXF KeyManager and TrustManager based on the Platform Global Configuration values");
            tlsClientParameters.setKeyManagers(keyManagers);
            tlsClientParameters.setTrustManagers(trustManagers);
        }
    }
}

From source file:org.apache.ws.security.saml.SignedSamlTokenHOKTest.java

public SignedSamlTokenHOKTest() throws Exception {
    WSSConfig.init();/*from  w w  w  .  j  ava  2s . c o  m*/
    // Load the issuer keystore
    issuerCrypto = new Merlin();
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    ClassLoader loader = Loader.getClassLoader(SignedSamlTokenHOKTest.class);
    InputStream input = Merlin.loadInputStream(loader, "keys/wss40_server.jks");
    keyStore.load(input, "security".toCharArray());
    ((Merlin) issuerCrypto).setKeyStore(keyStore);

    // Load the server truststore
    trustCrypto = new Merlin();
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    input = Merlin.loadInputStream(loader, "keys/wss40CA.jks");
    trustStore.load(input, "security".toCharArray());
    ((Merlin) trustCrypto).setTrustStore(trustStore);
}

From source file:projekat.rest_client.RestTemplateFactory.java

@Override
public void afterPropertiesSet() {

    fillTypesForRestService();/*from   w  w w .j  av a2s. c  om*/
    //za potrebe testirnja
    if (rest_keystore == null || "".equals(rest_keystore)) {
        rest_keystore = "/etc/keystores/nst2.jks";
        rest_keystore_password = "changeit";
        res_host_port = "8443";
        rest_hostname = "localhost";
    }
    InputStream keyStoreInputStream = null;
    try {
        keyStoreInputStream = new FileInputStream(rest_keystore);
        if (keyStoreInputStream == null) {
            throw new FileNotFoundException("");
        }
        final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        try {
            trustStore.load(keyStoreInputStream, rest_keystore_password.toCharArray());
        } finally {
            keyStoreInputStream.close();
        }
        SSLContext sslcontext = SSLContexts.custom()
                .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
                null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        auth = new HttpComponentsClientHttpRequestFactoryBasicAuth(
                new HttpHost(rest_hostname, Integer.parseInt(res_host_port), "https"), httpClient);
        auth.setConnectTimeout(60000);
        auth.setReadTimeout(180000);
        restTemplate = new RestTemplate(auth);
    } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException
            | KeyManagementException ex) {
        Logger.getLogger(RestTemplateFactory.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            keyStoreInputStream.close();
        } catch (Exception ex) {
            Logger.getLogger(RestTemplateFactory.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:it.macisamuele.network.WebApplicationClient.java

public boolean acceptAnyCertificate() {
    try {//from w  w  w . ja v  a2s . co  m
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        MySSLSocketFactory socketFactory = new MySSLSocketFactory(trustStore);
        socketFactory.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        asyncHttpClient.setSSLSocketFactory(socketFactory);
        return true;
    } catch (IOException | NoSuchAlgorithmException | CertificateException | UnrecoverableKeyException
            | KeyStoreException | KeyManagementException e) {
        e.printStackTrace();
        return false;
    }
}

From source file:org.apache.ws.security.saml.SamlNegativeTest.java

public SamlNegativeTest() throws Exception {
    WSSConfig.init();//  w w  w  .  j  a v a  2s. c  om
    // Load the issuer keystore
    issuerCrypto = new Merlin();
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    ClassLoader loader = Loader.getClassLoader(SamlNegativeTest.class);
    InputStream input = Merlin.loadInputStream(loader, "keys/wss40_server.jks");
    keyStore.load(input, "security".toCharArray());
    ((Merlin) issuerCrypto).setKeyStore(keyStore);

    // Load the server truststore
    trustCrypto = new Merlin();
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    input = Merlin.loadInputStream(loader, "keys/wss40CA.jks");
    trustStore.load(input, "security".toCharArray());
    ((Merlin) trustCrypto).setTrustStore(trustStore);
}

From source file:com.shekhargulati.reactivex.docker.client.ssl.DockerCertificates.java

private DockerCertificates(final Builder builder) throws DockerCertificateException {
    if ((builder.caCertPath == null) || (builder.clientCertPath == null) || (builder.clientKeyPath == null)) {
        throw new DockerCertificateException(
                "caCertPath, clientCertPath, and clientKeyPath must all be specified");
    }//w  w  w. j a v a  2s . co  m

    try {
        final CertificateFactory cf = CertificateFactory.getInstance("X.509");
        final Certificate caCert = cf.generateCertificate(Files.newInputStream(builder.caCertPath));
        final Certificate clientCert = cf.generateCertificate(Files.newInputStream(builder.clientCertPath));

        final PEMKeyPair clientKeyPair = (PEMKeyPair) new PEMParser(
                Files.newBufferedReader(builder.clientKeyPath, Charset.defaultCharset())).readObject();

        final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(
                clientKeyPair.getPrivateKeyInfo().getEncoded());
        final KeyFactory kf = KeyFactory.getInstance("RSA");
        final PrivateKey clientKey = kf.generatePrivate(spec);

        final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        trustStore.setEntry("ca", new KeyStore.TrustedCertificateEntry(caCert), null);

        final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, KEY_STORE_PASSWORD);
        keyStore.setCertificateEntry("client", clientCert);
        keyStore.setKeyEntry("key", clientKey, KEY_STORE_PASSWORD, new Certificate[] { clientCert });

        this.sslContext = SSLContexts.custom().loadTrustMaterial(trustStore)
                .loadKeyMaterial(keyStore, KEY_STORE_PASSWORD).useTLS().build();
    } catch (CertificateException | IOException | NoSuchAlgorithmException | InvalidKeySpecException
            | KeyStoreException | UnrecoverableKeyException | KeyManagementException e) {
        throw new DockerCertificateException(e);
    }
}

From source file:psiprobe.controllers.certificates.ListCertificatesController.java

/**
 * Gets the certificates.//from w  w  w .  j a v  a2  s .  c o m
 *
 * @param storeType the store type
 * @param storeFile the store file
 * @param storePassword the store password
 * @return the certificates
 * @throws Exception the exception
 */
public List<Cert> getCertificates(String storeType, String storeFile, String storePassword) throws Exception {
    KeyStore keyStore;

    // Get key store
    if (storeType != null) {
        keyStore = KeyStore.getInstance(storeType);
    } else {
        keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    }

    // Get password
    char[] password = null;
    if (storePassword != null) {
        password = storePassword.toCharArray();
    }

    // Load key store from file
    try (InputStream storeInput = getStoreInputStream(storeFile)) {
        keyStore.load(storeInput, password);
    } catch (IOException e) {
        logger.error("Error loading store file {}", storeFile, e);
        return null;
    }

    List<Cert> certs = new ArrayList<>();

    for (String alias : Collections.list(keyStore.aliases())) {

        Certificate[] certificateChains = keyStore.getCertificateChain(alias);

        if (certificateChains != null) {
            for (Certificate certificateChain : certificateChains) {
                X509Certificate x509Cert = (X509Certificate) certificateChain;
                addToStore(certs, alias, x509Cert);
            }
        } else {
            X509Certificate x509Cert = (X509Certificate) keyStore.getCertificate(alias);
            addToStore(certs, alias, x509Cert);
        }
    }
    return certs;
}

From source file:com.guster.skywebservice.library.webservice.SkyHttp.java

public static void setSSLCertificate(InputStream certificateFile) throws CertificateException, IOException,
        KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    Certificate cert = cf.generateCertificate(certificateFile);

    certificateFile.close();//from w  w  w . j a  va  2  s.c  o  m

    // create a keystore containing the certificate
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(null, null);
    keyStore.setCertificateEntry("ca", cert);

    // create a trust manager for our certificate
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(keyStore);

    // create a SSLContext that uses our trust manager
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, tmf.getTrustManagers(), null);

    // set socket factory
    setSSLSocketFactory(context.getSocketFactory());
}