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.vangent.hieos.services.sts.util.STSUtil.java

/**
 * //from  w w  w  .jav  a2 s.  c  om
 * @param stsConfig
 * @return
 * @throws STSException
 */
public static KeyStore getTrustStore(STSConfig stsConfig) throws STSException {
    KeyStore ks;
    try {
        ks = KeyStore.getInstance(KeyStore.getDefaultType());
        String trustStorePassword = stsConfig.getTrustStorePassword();
        char[] password = trustStorePassword.toCharArray();
        FileInputStream fis = new FileInputStream(stsConfig.getTrustStoreFileName());
        ks.load(fis, password);
        fis.close();
    } catch (Exception ex) {
        throw new STSException("Problem loading truststore: " + ex.getMessage());
    }
    return ks;
}

From source file:com.osbitools.ws.shared.auth.SamlSecurityProvider.java

@Override
public void init(ServletContext ctx, Properties properties) throws RuntimeException {
    super.init(ctx, properties);

    // Read keystore password
    String kpwd = properties.getProperty("keystore.pwd");
    if (Utils.isEmpty(kpwd))
        throw new RuntimeException("Keystore password is not found");
    byte[] bkpwd = Base64.decode(kpwd);

    // Read default service provider name which is same as servlet context
    String cpath = properties.getProperty("cpath").substring(1);

    // Read actual service provider name (if defined)
    _sname = properties.getProperty("saml." + cpath + ".sp_name", cpath);

    // Read service location
    _sloc = properties.getProperty("saml." + cpath + ".sp_loc");

    // Read service provider keystore password
    String spwd = properties.getProperty("keystore." + cpath + ".pwd");
    if (Utils.isEmpty(spwd))
        throw new RuntimeException("Keystore password for '" + cpath + "' key is not found");
    byte[] bspwd = Base64.decode(spwd);

    // Initialize internal variables
    try {//from w w w.  java2  s . c om
        DefaultBootstrap.bootstrap();
    } catch (ConfigurationException e) {
        throw new RuntimeException(e);
    }

    _bf = Configuration.getBuilderFactory();

    // Read servlet config directory
    String cdir = properties.getProperty("cdir");

    // Load service provider certificates
    KeyStore ks;
    try {
        ks = KeyStore.getInstance(KeyStore.getDefaultType());
    } catch (KeyStoreException e) {
        throw new RuntimeException(e);
    }

    FileInputStream fis;
    try {
        fis = new FileInputStream(cdir + File.separator + Constants.KEYSTORE_FILE);
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    }

    try {
        ks.load(fis, new String(bkpwd).toCharArray());
    } catch (NoSuchAlgorithmException | CertificateException | IOException e) {
        throw new RuntimeException(e);
    }

    // Remember private key for sign request
    try {
        _key = (PrivateKey) ks.getKey(cpath, new String(bspwd).toCharArray());
    } catch (UnrecoverableKeyException | KeyStoreException | NoSuchAlgorithmException e) {
        throw new RuntimeException("Error loading key for alias '" + cpath + "'. ERROR: " + e.getMessage());
    }

    if (_key == null)
        throw new RuntimeException("Key for alias '" + cpath + "' not found in keystore ");

    try {
        fis.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    Map<String, String> passwordMap = new HashMap<String, String>();
    passwordMap.put(cpath, new String(bspwd));
    KeyStoreCredentialResolver resolver = new KeyStoreCredentialResolver(ks, passwordMap);

    Criteria criteria = new EntityIDCriteria(cpath);
    CriteriaSet criteriaSet = new CriteriaSet(criteria);

    try {
        _scred = (X509Credential) resolver.resolveSingle(criteriaSet);
    } catch (SecurityException e) {
        throw new RuntimeException(e);
    }

    // Load IDP Metadata
    // Get parser pool manager
    _pmgr = new BasicParserPool();
    _pmgr.setNamespaceAware(true);

    // Parse metadata file
    InputStream in;
    try {
        in = new FileInputStream(cdir + File.separator + Constants.IDP_METADATA_FILE);
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    }

    Document doc;
    try {
        doc = _pmgr.parse(in);
    } catch (XMLParserException e) {
        throw new RuntimeException(e);
    }

    try {
        in.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    Element root = doc.getDocumentElement();

    UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
    Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(root);

    EntityDescriptor eds;
    try {
        eds = (EntityDescriptor) unmarshaller.unmarshall(root);
    } catch (UnmarshallingException e) {
        throw new RuntimeException(e);
    }
    _idp = eds.getEntityID();

    DOMMetadataProvider mp = new DOMMetadataProvider(root);
    mp.setRequireValidMetadata(true);
    // mp.setParserPool(new BasicParserPool());
    try {
        mp.initialize();
    } catch (MetadataProviderException e) {
        throw new RuntimeException(e);
    }

    MetadataCredentialResolverFactory crf = MetadataCredentialResolverFactory.getFactory();

    MetadataCredentialResolver cr = crf.getInstance(mp);

    // Look for signing key
    CriteriaSet cs = new CriteriaSet();
    cs.add((Criteria) new MetadataCriteria(IDPSSODescriptor.DEFAULT_ELEMENT_NAME, SAMLConstants.SAML20P_NS));
    cs.add(new EntityIDCriteria(_idp));
    cs.add(new UsageCriteria(UsageType.SIGNING));

    try {
        _cred = (X509Credential) cr.resolveSingle(cs);
    } catch (SecurityException e) {
        throw new RuntimeException(e);
    }

    if (_cred == null)
        throw new RuntimeException("Signing Key Descriptors " + "not found in IDP Entity Descriptor");

    IDPSSODescriptor idps = eds.getIDPSSODescriptor(SAMLConstants.SAML20P_NS);

    for (SingleSignOnService sss : idps.getSingleSignOnServices()) {
        if (sss.getBinding().equals(SAMLConstants.SAML2_POST_BINDING_URI)) {
            _login = sss.getLocation();
            break;
        }
    }

    if (_login == null)
        throw new RuntimeException("IDP SSO POST Redirecting " + "Location not found in IDP Entity Descriptor");

    // Get Single Logout Service
    for (SingleLogoutService slo : idps.getSingleLogoutServices()) {
        if (slo.getBinding().equals(SAMLConstants.SAML2_SOAP11_BINDING_URI))
            _logout = slo.getLocation();
    }

    if (_logout == null)
        throw new RuntimeException("IDP SLO SOAP " + "Location not found in IDP Entity Descriptor");
}

From source file:de.geomobile.joined.api.service.JOWebService.java

/**
 * @return//from  ww  w.  j  ava2 s .  c  o m
 */
private HttpClient getNewHttpClient() {
    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

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

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

From source file:com.num.mobiperf.Checkin.java

/**
 * Return an appropriately-configured HTTP client.
 *//* w  ww  .ja  v  a2  s .  co  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:com.mobicage.rpc.newxmpp.XMPPConfigurationFactory.java

private void pimpXMPPConfig(final ConnectionConfiguration config) {
    XMPPConnection.DEBUG_ENABLED = CloudConstants.XMPP_DEBUG;

    if (CloudConstants.USE_TRUSTSTORE) {
        config.setVerifyChainEnabled(true);
        config.setSelfSignedCertificateEnabled(true);
        config.setVerifyRootCAEnabled(true);
        config.setNotMatchingDomainCheckEnabled(true);
        config.setExpiredCertificatesCheckEnabled(false);

        File f1 = new File(App.getContext().getCacheDir() + "/truststore.bks");
        if (!f1.exists()) {
            copyAsset("truststore.bks", f1.getPath());
        }//from  www .  java 2s  . c o m
        config.setSecurityMode(SecurityMode.required);

        config.setTruststoreType("BKS");
        config.setTruststorePassword("rogerthat");
        config.setTruststorePath(f1.getPath());
    } else {
        if (CloudConstants.XMPP_MUST_VALIDATE_SSL_CERTIFICATE) {
            config.setVerifyChainEnabled(true);
            config.setSelfSignedCertificateEnabled(false);
            config.setVerifyRootCAEnabled(true);
            config.setNotMatchingDomainCheckEnabled(true);
            config.setExpiredCertificatesCheckEnabled(true);

            config.setSecurityMode(SecurityMode.required);
        } else {
            L.w("XMPP SSL checks are disabled. NEVER USE THIS IN PRODUCTION !");

            config.setVerifyChainEnabled(false);
            config.setSelfSignedCertificateEnabled(true);
            config.setVerifyRootCAEnabled(false);
            config.setNotMatchingDomainCheckEnabled(false);
            config.setExpiredCertificatesCheckEnabled(false);

            config.setSecurityMode(SecurityMode.enabled);
        }

        final String trustStorePath = System.getProperty("javax.net.ssl.trustStore");
        config.setTruststorePath(trustStorePath);
        config.setTruststoreType(KeyStore.getDefaultType());
    }

    config.setSendPresence(true);
    config.setRosterLoadedAtLogin(false);
    config.setReconnectionAllowed(true);
}

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

/**
 * Same as sendHttpGet above, except that we return the HttpClient so that it can
 * subsequently be re-used (for e.g. logout)
 *//* w w w.j  a  v a 2 s.  c om*/
public static CloseableHttpClient sendHttpGetForSignIn(String url, String user, String password,
        int returnCodeIDP, int returnCodeRP, int idpPort) throws Exception {

    CloseableHttpClient httpClient = null;
    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();

    Assert.assertTrue("IDP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: "
            + returnCodeIDP + "]", returnCodeIDP == response.getStatusLine().getStatusCode());

    if (response.getStatusLine().getStatusCode() != 200) {
        return null;
    }

    //            Redirect to a POST is not supported without user interaction
    //            http://www.ietf.org/rfc/rfc2616.txt
    //            If the 301 status code is received in response to a request other
    //            than GET or HEAD, the user agent MUST NOT automatically redirect the
    //            request unless it can be confirmed by the user, since this might
    //            change the conditions under which the request was issued.

    Source source = new Source(EntityUtils.toString(entity));
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    FormFields formFields = source.getFormFields();

    List<Element> forms = source.getAllElements(HTMLElementName.FORM);
    Assert.assertEquals("Only one form expected but got " + forms.size(), 1, forms.size());
    String postUrl = forms.get(0).getAttributeValue("action");

    Assert.assertNotNull("Form field 'wa' not found", formFields.get("wa"));
    Assert.assertNotNull("Form field 'wresult' not found", formFields.get("wresult"));

    for (FormField formField : formFields) {
        if (formField.getUserValueCount() != 0) {
            nvps.add(new BasicNameValuePair(formField.getName(), formField.getValues().get(0)));
        }
    }
    HttpPost httppost = new HttpPost(postUrl);
    httppost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));

    response = httpClient.execute(httppost);

    entity = response.getEntity();
    Assert.assertTrue("RP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: "
            + returnCodeRP + "]", returnCodeRP == response.getStatusLine().getStatusCode());

    String responseStr = EntityUtils.toString(entity);
    Assert.assertTrue("Principal not " + user, responseStr.indexOf("userPrincipal=" + user) > 0);

    return httpClient;
}

From source file:net.jmhertlein.mcanalytics.api.auth.SSLUtil.java

public static KeyStore newKeyStore() {
    KeyStore store;// ww w .  ja  v  a 2s . c  o  m
    try {
        store = KeyStore.getInstance(KeyStore.getDefaultType());
        store.load(null, null);
        return store;
    } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException ex) {
        Logger.getLogger(SSLUtil.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }

}

From source file:com.android.volley.toolbox.http.HttpClientStack.java

public static org.apache.http.conn.ssl.SSLSocketFactory getSSLSocketFactory() {
    SSLSocketFactory sf = null;/*from www . jav a  2 s. c  o m*/
    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        sf = new JindunSSLSocketFactory(trustStore);
        //          sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return sf;
}

From source file:org.glite.slcs.httpclient.ssl.ExtendedProtocolSocketFactory.java

/**
 * Creates and loads a keystore./*from  w  w w.j  a  v  a2 s.  c o m*/
 * 
 * @param path
 *            The keystore filename in classpath or the absolute filename
 * @param password
 *            The keystore password.
 * @return A new initialized {@link KeyStore} containing the client certificate and key.
 * @throws KeyStoreException
 * @throws NoSuchAlgorithmException
 * @throws CertificateException
 * @throws IOException
 *             If an error occurs while loading the truststore.
 */
private KeyStore createKeyStore(String path, String password)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
    if (path == null) {
        throw new IllegalArgumentException("Key keystore path may not be null");
    }
    if (password == null) {
        throw new IllegalArgumentException("Key keystore password may not be null");
    }
    // first search file in classpath, then as absolute filename
    LOG.debug("Load keystore from classpath: /" + path);
    InputStream is = getClass().getResourceAsStream("/" + path);
    if (is == null) {
        LOG.debug("Not in classpath, load keystore from file: " + path);
        is = new FileInputStream(path);
    }
    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    keystore.load(is, password.toCharArray());
    return keystore;
}

From source file:net.sf.jsignpdf.SignPdfForm.java

/**
 * Loads properties saved by previous run of application
 *///from  www . j a  v a 2  s.c o m
private void updateFromOptions() {
    if (StringUtils.isNotEmpty(options.getKsType())) {
        cbKeystoreType.setSelectedItem(options.getKsType());
    } else if (cbKeystoreType.getSelectedItem() == null) {
        cbKeystoreType.setSelectedItem(KeyStore.getDefaultType());
    }
    chkbAdvanced.setSelected(options.isAdvanced());
    tfKeystoreFile.setText(options.getKsFile());
    pfKeystorePwd.setText(options.getKsPasswdStr());
    chkbStorePwd.setSelected(options.isStorePasswords());
    cbAlias.setSelectedItem(options.getKeyAlias());
    pfKeyPwd.setText(options.getKeyPasswdStr());
    tfInPdfFile.setText(options.getInFile());
    cbPdfEncryption.setSelectedItem(options.getPdfEncryption());
    pfPdfOwnerPwd.setText(options.getPdfOwnerPwdStr());
    pfPdfUserPwd.setText(options.getPdfUserPwdStr());
    tfEncCertFile.setText(options.getPdfEncryptionCertFile());
    tfOutPdfFile.setText(options.getOutFile());
    tfReason.setText(options.getReason());
    tfLocation.setText(options.getLocation());
    tfContact.setText(options.getContact());
    cbCertLevel.setSelectedItem(options.getCertLevel());
    cbHashAlgorithm.setSelectedItem(options.getHashAlgorithm());
    chkbAppendSignature.setSelected(options.isAppend());

    cbPrinting.setSelectedItem(options.getRightPrinting());
    chkbAllowCopy.setSelected(options.isRightCopy());
    chkbAllowAssembly.setSelected(options.isRightAssembly());
    chkbAllowFillIn.setSelected(options.isRightFillIn());
    chkbAllowScreenReaders.setSelected(options.isRightScreanReaders());
    chkbAllowModifyAnnotations.setSelected(options.isRightModifyAnnotations());
    chkbAllowModifyContent.setSelected(options.isRightModifyContents());

    chkbVisibleSig.setSelected(options.isVisible());

    refreshView();
    pack();
}