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.openiot.gsn.http.rest.PushRemoteWrapper.java

public boolean initialize() {

    try {/*from w  w w  .ja va  2s .c o  m*/
        initParams = new RemoteWrapperParamParser(getActiveAddressBean(), true);
        uid = Math.random();

        postParameters = new ArrayList<NameValuePair>();
        postParameters.add(new BasicNameValuePair(PushDelivery.NOTIFICATION_ID_KEY, Double.toString(uid)));
        postParameters.add(
                new BasicNameValuePair(PushDelivery.LOCAL_CONTACT_POINT, initParams.getLocalContactPoint()));
        // Init the http client
        if (initParams.isSSLRequired()) {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(new FileInputStream(new File("conf/servertestkeystore")),
                    Main.getContainerConfig().getSSLKeyStorePassword().toCharArray());
            SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
            socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            int sslPort = Main.getContainerConfig().getSSLPort() > 0 ? Main.getContainerConfig().getSSLPort()
                    : ContainerConfig.DEFAULT_SSL_PORT;
            Scheme sch = new Scheme("https", socketFactory, sslPort);
            httpclient.getConnectionManager().getSchemeRegistry().register(sch);
        }
        Scheme plainsch = new Scheme("http", PlainSocketFactory.getSocketFactory(),
                Main.getContainerConfig().getContainerPort());
        httpclient.getConnectionManager().getSchemeRegistry().register(plainsch);
        //
        lastReceivedTimestamp = initParams.getStartTime();
        structure = registerAndGetStructure();
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        NotificationRegistry.getInstance().removeNotification(uid);
        return false;
    }

    return true;
}

From source file:org.opennms.netmgt.provision.server.SSLServer.java

/**
 * <p>init</p>/*from  w w w  . ja  v a 2 s.c  o m*/
 *
 * @throws java.lang.Exception if any.
 */
@Override
public void init() throws Exception {
    super.init();
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(getKeyManagerAlgorithm(), getKeyManagerProvider());
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    char[] password = getPassword().toCharArray();

    java.io.FileInputStream fis = null;
    try {
        fis = new java.io.FileInputStream(getPathToKeyStore());
        ks.load(fis, password);
    } finally {
        if (fis != null) {
            fis.close();
        }
    }

    kmf.init(ks, password);
    KeyManager[] km = kmf.getKeyManagers();

    SSLContext sslContext = SSLContext.getInstance(getSslContextProtocol());
    sslContext.init(km, null, new SecureRandom());
    SSLServerSocketFactory serverFactory = sslContext.getServerSocketFactory();
    setServerSocket(serverFactory.createServerSocket(getPort()));
    onInit();
}

From source file:com.cloudbees.jenkins.support.impl.RootCAs.java

public static void getRootCAList(StringWriter writer) {
    KeyStore instance = null;//from  www . j av  a 2  s. c  o  m
    try {
        instance = KeyStore.getInstance(KeyStore.getDefaultType());
        Enumeration<String> aliases = instance.aliases();
        while (aliases.hasMoreElements()) {
            String s = aliases.nextElement();
            writer.append("========");
            writer.append("Alias: " + s);
            writer.append(instance.getCertificate(s).getPublicKey().toString());
            writer.append("Trusted certificate: " + instance.isCertificateEntry(s));
        }
    } catch (KeyStoreException e) {
        writer.write(Functions.printThrowable(e));
    }
}

From source file:eu.trentorise.smartcampus.ac.network.HttpsClientBuilder.java

private static HttpClient getWildcartHttpClient(HttpParams inParams) {
    HttpClient client = null;/*  ww w  .  j ava2 s .  co m*/

    HttpParams params = inParams != null ? inParams : new BasicHttpParams();

    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

        SSLSocketFactory sslSocketFactory = new CustomSSLSocketFactory(trustStore);
        final X509HostnameVerifier delegate = sslSocketFactory.getHostnameVerifier();
        if (!(delegate instanceof WildcardVerifier)) {
            sslSocketFactory.setHostnameVerifier(new WildcardVerifier(delegate));
        }
        registry.register(new Scheme("https", sslSocketFactory, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        client = new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        client = new DefaultHttpClient(params);
    }

    return client;
}

From source file:org.openmrs.module.rheapocadapter.handler.ConnectionHandler.java

public ConnectionHandler() throws KeyStoreException, NoSuchAlgorithmException, CertificateException,
        IOException, KeyManagementException {

    InputStream keyStoreStream = getClass().getResourceAsStream("/web/module/resources/truststore.jks");

    // Load the keyStore
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(keyStoreStream, "Jembi#123".toCharArray());
    keyStoreStream.close();/*w  w  w .j a  va2 s .  co  m*/

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(keyStore);

    SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(null, tmf.getTrustManagers(), null);

    // set SSL Factory to be used for all HTTPS connections
    sslFactory = ctx.getSocketFactory();
    setImplementationId();
}

From source file:org.hyperic.util.security.KeystoreManager.java

public KeyStore getKeyStore(KeystoreConfig keystoreConfig) throws KeyStoreException, IOException {
    FileInputStream keyStoreFileInputStream = null;

    String filePath = keystoreConfig.getFilePath();
    String filePassword = keystoreConfig.getFilePassword();

    //check if keystoreConfig valid (block if it's null or "")
    String errorMsg = "";
    if (keystoreConfig.getAlias() == null) {
        errorMsg += " alias is null. ";
    }/*from w ww .j a  va 2 s .c  o  m*/
    if (keystoreConfig.getFilePath() == null) {
        errorMsg += " filePath is null. ";
    }
    if (keystoreConfig.getFilePassword() == null) {
        errorMsg += " password is null. ";
    }
    if (!"".equals(errorMsg)) {
        throw new KeyStoreException(errorMsg);
    }

    try {
        KeyStore keystore = DbKeyStore.getInstance(KeyStore.getDefaultType(), isDB);
        File file = new File(filePath);
        char[] password = null;

        if (!file.exists()) {
            // ...if file doesn't exist, and path was user specified throw IOException...
            if (StringUtils.hasText(filePath) && !keystoreConfig.isHqDefault()) {
                throw new IOException("User specified keystore [" + filePath + "] does not exist.");
            }

            password = filePassword.toCharArray();
            createInternalKeystore(keystoreConfig);
            FileUtil.setReadWriteOnlyByOwner(file);
        }

        // ...keystore exist, so init the file input stream...
        keyStoreFileInputStream = new FileInputStream(file);

        keystore.load(keyStoreFileInputStream, password);

        return keystore;
    } catch (NoSuchAlgorithmException e) {
        // can't check integrity of keystore, if this happens we're kind of screwed
        // is there anything we can do to self heal this problem?
        errorMsg = "The algorithm used to check the integrity of the keystore cannot be found.";
        throw new KeyStoreException(errorMsg, e);
    } catch (CertificateException e) {
        // there are some corrupted certificates in the keystore, a bad thing
        // is there anything we can do to self heal this problem?
        errorMsg = "Keystore cannot be loaded. One possibility is that the password is incorrect.";
        throw new KeyStoreException(errorMsg, e);
    } finally {
        if (keyStoreFileInputStream != null) {
            keyStoreFileInputStream.close();
            keyStoreFileInputStream = null;
        }
    }
}

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

public SamlReferenceTest() throws Exception {
    WSSConfig.init();//from   w  w  w .  j  av a2s . 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:com.amazon.alexa.avs.auth.companionservice.CompanionServiceClient.java

/**
 * Loads the CA certificate into an in-memory keystore and creates an {@link SSLSocketFactory}.
 *
 * @return SSLSocketFactory/*from www.  jav a 2s  .co  m*/
 */
public SSLSocketFactory getPinnedSSLSocketFactory() {
    InputStream caCertInputStream = null;
    InputStream clientKeyPair = null;
    try {
        // Load the CA certificate into memory
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        caCertInputStream = new FileInputStream(deviceConfig.getCompanionServiceInfo().getSslCaCert());
        Certificate caCert = cf.generateCertificate(caCertInputStream);

        // Load the CA certificate into the trusted KeyStore
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        trustStore.setCertificateEntry("myca", caCert);

        // Create a TrustManagerFactory with the trusted KeyStore
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);

        // Load the client certificate and private key into another KeyStore
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        clientKeyPair = new FileInputStream(deviceConfig.getCompanionServiceInfo().getSslClientKeyStore());
        keyStore.load(clientKeyPair,
                deviceConfig.getCompanionServiceInfo().getSslClientKeyStorePassphrase().toCharArray());

        // Create a TrustManagerFactory with the client key pair KeyStore
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore,
                deviceConfig.getCompanionServiceInfo().getSslClientKeyStorePassphrase().toCharArray());

        // Initialize the SSLContext and return an SSLSocketFactory;
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

        return sc.getSocketFactory();
    } catch (CertificateException | KeyStoreException | UnrecoverableKeyException | NoSuchAlgorithmException
            | IOException | KeyManagementException e) {
        throw new RuntimeException("The KeyStore for contacting the Companion Service could not be loaded.", e);
    } finally {
        IOUtils.closeQuietly(caCertInputStream);
        IOUtils.closeQuietly(clientKeyPair);
    }
}

From source file:groovyx.net.http.AuthConfig.java

/**
 * Sets a certificate to be used for SSL authentication.  See
 * {@link Class#getResource(String)} for how to get a URL from a resource
 * on the classpath.//from  w  ww. j  a v a  2s .  co  m
 * @param certURL URL to a JKS keystore where the certificate is stored.
 * @param password password to decrypt the keystore
 */
public void certificate(String certURL, String password) throws GeneralSecurityException, IOException {

    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    InputStream jksStream = new URL(certURL).openStream();
    try {
        keyStore.load(jksStream, password.toCharArray());
    } finally {
        jksStream.close();
    }

    SSLSocketFactory ssl = new SSLSocketFactory(keyStore, password);
    ssl.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);

    builder.getClient().getConnectionManager().getSchemeRegistry().register(new Scheme("https", ssl, 443));
}

From source file:com.vkassin.mtrade.CSPLicense.java

public HttpClient getNewHttpClient() {
    try {/*from ww  w .java  2  s  . c o  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();
    }
}