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.adeptnet.auth.saml.SAMLClient.java

private Signature getSignature() {
    try {//www .j a  v  a 2 s.  c o m
        final char[] jksPassword = config.getKeystorePassword();
        final String alias = config.getCertificateAlias();
        final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        try (final FileInputStream fileInputStream = new FileInputStream(config.getKeystore())) {
            keyStore.load(fileInputStream, jksPassword);
        }
        final KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias,
                new KeyStore.PasswordProtection(jksPassword));
        final PrivateKey privateKey = privateKeyEntry.getPrivateKey();
        final X509Certificate certificate = (X509Certificate) privateKeyEntry.getCertificate();

        final BasicX509Credential credential = new BasicX509Credential();
        credential.setEntityCertificate(certificate);
        credential.setPrivateKey(privateKey);

        final Signature signature = (Signature) org.opensaml.xml.Configuration.getBuilderFactory()
                .getBuilder(org.opensaml.xml.signature.Signature.DEFAULT_ELEMENT_NAME)
                .buildObject(org.opensaml.xml.signature.Signature.DEFAULT_ELEMENT_NAME);
        signature.setSigningCredential(credential);
        final SecurityConfiguration securityConfiguration = Configuration.getGlobalSecurityConfiguration();
        final String keyInfoGeneratorProfile = null;
        SecurityHelper.prepareSignatureParams(signature, credential, securityConfiguration,
                keyInfoGeneratorProfile);
        return signature;
    } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException
            | UnrecoverableEntryException | SecurityException ex) {
        Logger.getLogger(SAMLClient.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}

From source file:com.dongfang.dicos.sina.UtilSina.java

public static HttpClient getNewHttpClient(Context context) {
    try {//from   w  w  w  .  j a  va 2s .  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();

        HttpConnectionParams.setConnectionTimeout(params, 10000);
        HttpConnectionParams.setSoTimeout(params, 10000);

        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);

        // Set the default socket timeout (SO_TIMEOUT) // in
        // milliseconds which is the timeout for waiting for data.
        HttpConnectionParams.setConnectionTimeout(params, UtilSina.SET_CONNECTION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, UtilSina.SET_SOCKET_TIMEOUT);
        HttpClient client = new DefaultHttpClient(ccm, params);
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        if (!wifiManager.isWifiEnabled()) {
            // ??APN
            Uri uri = Uri.parse("content://telephony/carriers/preferapn");
            Cursor mCursor = context.getContentResolver().query(uri, null, null, null, null);
            if (mCursor != null && mCursor.moveToFirst()) {
                // ???
                String proxyStr = mCursor.getString(mCursor.getColumnIndex("proxy"));
                if (proxyStr != null && proxyStr.trim().length() > 0) {
                    HttpHost proxy = new HttpHost(proxyStr, 80);
                    client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
                }
                mCursor.close();
            }
        }
        return client;
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

From source file:ddf.security.realm.sts.StsRealm.java

/**
 * Setup trust store for SSL client./* ww  w  . jav  a  2 s. co m*/
 */
private void setupTrustStore(TLSClientParameters tlsParams, String trustStorePath, String trustStorePassword) {
    File trustStoreFile = new File(trustStorePath);
    if (trustStoreFile.exists() && trustStorePassword != null) {
        KeyStore trustStore = null;
        FileInputStream fis = null;

        try {
            trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            fis = new FileInputStream(trustStoreFile);
            LOGGER.debug("Loading trustStore");
            trustStore.load(fis, trustStorePassword.toCharArray());
            TrustManagerFactory trustFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustFactory.init(trustStore);
            LOGGER.debug("trust manager factory initialized");
            TrustManager[] tm = trustFactory.getTrustManagers();
            tlsParams.setTrustManagers(tm);

        } catch (FileNotFoundException e) {
            LOGGER.error("Unable to find SSL store: " + trustStorePath, e);
        } catch (IOException e) {
            LOGGER.error("Unable to load trust store. " + trustStore, e);
        } catch (CertificateException e) {
            LOGGER.error("Unable to load certificates from trust store. " + trustStore, e);
        } catch (KeyStoreException e) {
            LOGGER.error("Unable to read trust store: ", e);
        } catch (NoSuchAlgorithmException e) {
            LOGGER.error("Problems creating SSL socket. Usually this is "
                    + "referring to the certificate sent by the server not being trusted by the client.", e);
        } finally {
            IOUtils.closeQuietly(fis);
        }
    }
}

From source file:io.apiman.gateway.platforms.servlet.connectors.ssl.SSLSessionStrategyFactory.java

private static SSLContextBuilder loadKeyMaterial(SSLContextBuilder builder, File file, char[] ksp, char[] kp,
        PrivateKeyStrategy privateKeyStrategy) throws NoSuchAlgorithmException, KeyStoreException,
        UnrecoverableKeyException, CertificateException, IOException {
    Args.notNull(file, "Keystore file"); //$NON-NLS-1$
    final KeyStore identityStore = KeyStore.getInstance(KeyStore.getDefaultType());
    final FileInputStream instream = new FileInputStream(file);
    try {//w w  w.j a  va  2  s . c  om
        identityStore.load(instream, ksp);
    } finally {
        instream.close();
    }
    return builder.loadKeyMaterial(identityStore, kp, privateKeyStrategy);
}

From source file:com.mobilyzer.Checkin.java

/**
 * Return an appropriately-configured HTTP client.
 *///from   w w w .  jav a2 s .  c o  m
private HttpClient getNewHttpClient() {
    DefaultHttpClient client;
    try {
        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);

        HttpConnectionParams.setConnectionTimeout(params, POST_TIMEOUT_MILLISEC);
        HttpConnectionParams.setSoTimeout(params, POST_TIMEOUT_MILLISEC);

        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);
        client = new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        Logger.w("Unable to create SSL HTTP client", e);
        client = new DefaultHttpClient();
    }

    // TODO(mdw): For some reason this is not sending the cookie to the
    // test server, probably because the cookie itself is not properly
    // initialized. Below I manually set the Cookie header instead.
    CookieStore store = new BasicCookieStore();
    store.addCookie(authCookie);
    client.setCookieStore(store);
    return client;
}

From source file:org.alfresco.encryption.AlfrescoKeyStoreImpl.java

/**
 * Initializes class/*from   w  w w  .ja v  a 2 s  .  c  om*/
 */
private void safeInit() {
    PropertyCheck.mandatory(this, "location", getKeyStoreParameters().getLocation());

    // Make sure we choose the default type, if required
    if (getKeyStoreParameters().getType() == null) {
        keyStoreParameters.setType(KeyStore.getDefaultType());
    }

    writeLock.lock();
    try {
        keys = loadKeyStore(keyStoreParameters);
        backupKeys = loadKeyStore(backupKeyStoreParameters);
    } finally {
        writeLock.unlock();
    }
}

From source file:de.extra.client.plugins.outputplugin.transport.ExtraTransportHttp.java

/**
 * Sets up the Truststore.//from  w  ww . j av a  2s  .  c  om
 * 
 * @param extraConnectData
 * @return
 */
private void setupTruststore(final HttpOutputPluginConnectConfiguration extraConnectData)
        throws ExtraTransportException {

    // Load TrustStoreLocation from properties
    String truststoreLocation = extraConnectData.getSslTruststoreLocation();

    LOG.debug("TruststoreLoc: " + truststoreLocation);

    // If no location specified -> fallback to JRE default
    if (truststoreLocation == null || truststoreLocation.length() == 0) {
        truststoreLocation = System.getProperty("java.home") + File.separatorChar + "lib" + File.separatorChar
                + "security" + File.separatorChar + "cacerts";
    }

    LOG.debug("TruststoreLoc: " + truststoreLocation);

    try {
        // Create keystore instance
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        // KeyStore ks = KeyStore.getInstance("PKCS12");

        // Load keystore values
        FileInputStream fi = new FileInputStream(truststoreLocation);
        ks.load(fi, extraConnectData.getSslTruststorePassword().toCharArray());
        fi.close();

        // Create new certificate based on stored value
        java.security.cert.CertificateFactory certFactory = CertificateFactory.getInstance("X.509");

        X509Certificate cert = (X509Certificate) certFactory
                .generateCertificate(new ByteArrayInputStream(extraConnectData.getSslCertificate().getBytes()));

        // Check if certificate is not already stored -> store and save
        if (extraConnectData.isSslCertificateRefresh() || ks.getCertificateAlias(cert) == null) {

            LOG.info("Zertifikat wird eingetragen");

            ks.store(new FileOutputStream(truststoreLocation),
                    extraConnectData.getSslTruststorePassword().toCharArray());

        }

        // Set truststore location
        System.setProperty("javax.net.ssl.trustStore", truststoreLocation);

    } catch (KeyStoreException e) {
        throw new ExtraTransportException("Fehler bei Zugriff auf Keystore.", e);
    } catch (FileNotFoundException e) {
        throw new ExtraTransportException("Fehler beim Laden des Keystore.", e);
    } catch (NoSuchAlgorithmException e) {
        throw new ExtraTransportException("Fehler beim Laden des Crypto-Algorithmus.", e);
    } catch (CertificateException e) {
        throw new ExtraTransportException("Fehler beim Prfen des Zertifikats.", e);
    } catch (IOException e) {
        throw new ExtraTransportException("Fehler bei I/O-Operation.", e);
    }
}

From source file:edu.vt.middleware.crypt.CryptProvider.java

/**
 * <p>This creates a <code>KeyStore</code> using the supplied type name.</p>
 *
 * @param  type  <code>String</code>
 *
 * @return  <code>KeyStore</code>
 *
 * @throws  CryptException  if the type is not available from any provider or
 * the provider is not available in the environment
 *///from   w  w w .ja va 2  s.  co  m
public static KeyStore getKeyStore(final String type) throws CryptException {
    final Log logger = LogFactory.getLog(CryptProvider.class);
    KeyStore store = null;
    String keyStoreType = type;
    if (keyStoreType == null) {
        keyStoreType = KeyStore.getDefaultType();
    }
    for (int i = 0; i < providers.length; i++) {
        try {
            store = KeyStore.getInstance(keyStoreType, providers[i]);
        } catch (KeyStoreException e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Could not get instance of keystore type " + type + " from " + providers[i]);
            }
        } catch (NoSuchProviderException e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Could not find provider " + providers[i]);
            }
        } finally {
            if (store != null) {
                break;
            }
        }
    }
    if (store == null) {
        try {
            store = KeyStore.getInstance(keyStoreType);
        } catch (KeyStoreException e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Could not get instance of keystore type " + type);
            }
            throw new CryptException(e.getMessage());
        }
    }
    return store;
}

From source file:org.hyperledger.fabric.sdk.security.CryptoPrimitives.java

private void createTrustStore() throws CryptoException {
    try {//from  w ww . java2  s.  co m
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);
        setTrustStore(keyStore);
    } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException
            | InvalidArgumentException e) {
        throw new CryptoException("Cannot create trust store. Error: " + e.getMessage(), e);
    }
}