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.tremolosecurity.config.util.UnisonConfigManagerImpl.java

private void initSSL() throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException,
        KeyStoreException, CertificateException, FileNotFoundException, IOException {
    if (this.getKeyManagerFactory() == null) {
        return;/*from ww  w  .  j  a v  a2  s .  c  om*/
    }

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

    String cacertsPath = System.getProperty("javax.net.ssl.trustStore");
    if (cacertsPath == null) {
        cacertsPath = System.getProperty("java.home") + "/lib/security/cacerts";
    }

    cacerts.load(new FileInputStream(cacertsPath), null);

    Enumeration<String> enumer = cacerts.aliases();
    while (enumer.hasMoreElements()) {
        String alias = enumer.nextElement();
        java.security.cert.Certificate cert = cacerts.getCertificate(alias);
        this.ks.setCertificateEntry(alias, cert);
    }

    SSLContext sslctx = SSLContexts.custom().loadTrustMaterial(this.ks)
            .loadKeyMaterial(this.ks, this.cfg.getKeyStorePassword().toCharArray()).build();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslctx,
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    PlainConnectionSocketFactory sf = PlainConnectionSocketFactory.getSocketFactory();
    httpClientRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", sf)
            .register("https", sslsf).build();

    globalHttpClientConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES)
            .setRedirectsEnabled(false).setAuthenticationEnabled(false).build();

}

From source file:de.thorstenberger.examServer.pdf.signature.SignatureInfos.java

private KeyStore getKeystore() throws KeyStoreException {
    try {//from w w  w .  j  a v  a2 s .c o m
        final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(new FileInputStream(getKeystoreFile()), getKeystorePassword().toCharArray());
        return ks;
    } catch (final NoSuchAlgorithmException e) {
        throw new KeyStoreException(e);
    } catch (final CertificateException e) {
        throw new KeyStoreException(e);
    } catch (final FileNotFoundException e) {
        throw new KeyStoreException(e);
    } catch (final IOException e) {
        throw new KeyStoreException(e);
    }
}

From source file:org.jembi.rhea.rapidsms.GenerateORU_R01Alert.java

public void sendRequest(String msg)
        throws IOException, TransformerFactoryConfigurationError, TransformerException, KeyStoreException,
        NoSuchAlgorithmException, CertificateException, KeyManagementException {

    //log.info("Sending to RapidSMS:\n" + msg);

    // Get the key store that includes self-signed cert as a "trusted"
    // entry.//from   w  w  w  . j  a va  2  s  .  c o  m
    InputStream keyStoreStream = org.mule.util.IOUtils.getResourceAsStream("truststore.jks",
            GenerateORU_R01Alert.class);

    // Load the keyStore

    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(keyStoreStream, "Jembi#123".toCharArray());
    //log.info("KeyStoreStream = " + IOUtils.toString(keyStoreStream));
    keyStoreStream.close();

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

    callQueryFacility(msg);

}

From source file:com.arvato.thoroughly.util.RestTemplateUtil.java

private LayeredConnectionSocketFactory setUpSSL() {
    LayeredConnectionSocketFactory sslSF = null;
    try {//from w  ww.  j a  va2 s. c o m
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        SSLContext sslContext = SSLContexts.custom().useTLS()
                .loadTrustMaterial(trustStore, new AnyTrustStrategy()).build();
        sslSF = new SSLConnectionSocketFactory(sslContext,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    } catch (Exception e) {
        LOGGER.error(e.getMessage());
    }
    return sslSF;
}

From source file:br.gov.serpro.cert.AuthSSLProtocolSocketFactory.java

private static KeyStore createKeyStore(final URL[] urls, final String[] passwords)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    keystore.load(null);/*  w  ww.  j a  v a 2  s  .  c  o  m*/

    if (urls == null) {
        throw new IllegalArgumentException("Keystore urls may not be null");
    }

    if (passwords != null && passwords.length != urls.length) {
        throw new IllegalArgumentException("Urls and passwords arrays must have the same size");
    }

    LOG.debug("Initializing key store");

    for (int i = 0; i < urls.length; i++) {

        LOG.debug("Adding " + urls[i].toString() + " to internal keystore");
        KeyStore ks = KeyStore.getInstance("jks");
        InputStream is = null;
        try {
            is = urls[i].openStream();

            if (passwords == null) {
                ks.load(is, null);
            } else {
                ks.load(is, passwords[i] != null ? passwords[i].toCharArray() : null);
            }

            for (Enumeration<String> e = ks.aliases(); e.hasMoreElements();) {
                X509Certificate cert = (X509Certificate) ks.getCertificate(e.nextElement());
                keystore.setCertificateEntry(cert.getSubjectX500Principal().getName(), cert);
            }
        } catch (IOException e) {
            if (AuthSSLProtocolSocketFactory.setup.getParameter("debug").equalsIgnoreCase("true")) {
                System.out.println("Erro ao abrir URL: " + urls[i].toExternalForm());
            }
        } finally {
            if (is != null)
                is.close();
        }
    }
    return keystore;
}

From source file:test.SAMLAttributeQueryExample.java

/**
 * Build the HTTP client./*from   w  w w .j a  va  2 s.  co  m*/
 * 
 * @param idpCertificateFile path to idp certificate file
 * @param clientPrivateKeyFile path to client private key file
 * @param clientCertificateFile path to client certificate file
 * @return the HTTP client
 * @throws Exception if an error occurs
 */
@Nonnull
public static HttpClient buildHttpClient(@Nonnull final String idpCertificateFile,
        @Nonnull final String clientPrivateKeyFile, @Nonnull final String clientCertificateFile)
        throws Exception {

    X509Certificate idpCert = CertUtil.readCertificate(idpCertificateFile);
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    trustStore.load(null, null);
    trustStore.setCertificateEntry("idp", idpCert);

    PrivateKey clientPrivateKey = KeyPairUtil.readPrivateKey(clientPrivateKeyFile);
    X509Certificate clientCert = CertUtil.readCertificate(clientCertificateFile);
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(null, null);
    keyStore.setKeyEntry("me", clientPrivateKey, "secret".toCharArray(), new Certificate[] { clientCert });

    SSLContextBuilder sslContextBuilder = SSLContexts.custom();
    sslContextBuilder.loadTrustMaterial(trustStore);
    sslContextBuilder.loadKeyMaterial(keyStore, "secret".toCharArray());
    SSLContext sslcontext = sslContextBuilder.build();

    CloseableHttpClient httpClient = HttpClients.custom().setSslcontext(sslcontext).build();

    return httpClient;
}

From source file:org.apache.ws.security.message.SignaturePartsTest.java

/**
 * Test signing of a header through a STR Dereference Transform
 *//*from www .j  ava2  s .  c o  m*/
@SuppressWarnings("unchecked")
@org.junit.Test
public void testSOAPHeaderSTRTransform() throws Exception {
    // Construct issuer and user crypto instances
    Crypto 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);

    Crypto userCrypto = CryptoFactory.getInstance("wss40.properties");

    SAML1CallbackHandler callbackHandler = new SAML1CallbackHandler();
    callbackHandler.setStatement(SAML1CallbackHandler.Statement.AUTHN);
    callbackHandler.setConfirmationMethod(SAML1Constants.CONF_HOLDER_KEY);
    SAMLIssuer saml = new SAMLIssuerImpl();
    saml.setIssuerName("www.example.com");
    saml.setIssuerCrypto(issuerCrypto);
    saml.setIssuerKeyName("wss40_server");
    saml.setIssuerKeyPassword("security");
    saml.setSignAssertion(true);
    saml.setCallbackHandler(callbackHandler);
    AssertionWrapper assertion = saml.newAssertion();

    WSSecSignatureSAML wsSign = new WSSecSignatureSAML();
    wsSign.setKeyIdentifierType(WSConstants.BST_DIRECT_REFERENCE);
    wsSign.setUserInfo("wss40", "security");

    Document doc = SOAPUtil.toSOAPPart(SOAPMSG);
    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader(doc);

    List<WSEncryptionPart> parts = new ArrayList<WSEncryptionPart>();
    WSEncryptionPart encP = new WSEncryptionPart("STRTransform", "", "Element");
    parts.add(encP);
    wsSign.setParts(parts);

    //
    // set up for keyHolder
    //
    Document signedDoc = wsSign.build(doc, userCrypto, assertion, null, null, null, secHeader);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Signed SAML message (key holder):");
        String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(signedDoc);
        LOG.debug(outputString);
    }

    // Construct trust crypto instance
    Crypto 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);

    List<WSSecurityEngineResult> results = secEngine.processSecurityHeader(doc, null, null, trustCrypto);
    WSSecurityEngineResult stUnsignedActionResult = WSSecurityUtil.fetchActionResult(results,
            WSConstants.ST_SIGNED);
    AssertionWrapper receivedAssertion = (AssertionWrapper) stUnsignedActionResult
            .get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
    assertTrue(receivedAssertion != null);
    assertTrue(receivedAssertion.isSigned());

    WSSecurityEngineResult signActionResult = WSSecurityUtil.fetchActionResult(results, WSConstants.SIGN);
    assertTrue(signActionResult != null);
    assertFalse(signActionResult.isEmpty());
    final List<WSDataRef> refs = (List<WSDataRef>) signActionResult
            .get(WSSecurityEngineResult.TAG_DATA_REF_URIS);

    WSDataRef wsDataRef = (WSDataRef) refs.get(0);
    String xpath = wsDataRef.getXpath();
    assertEquals("/soapenv:Envelope/soapenv:Header/wsse:Security/saml1:Assertion", xpath);
}

From source file:com.sonatype.nexus.ssl.plugin.internal.TrustStoreImpl.java

private static KeyManager[] getSystemKeyManagers() throws Exception {
    KeyManagerFactory keyManagerFactory;

    String keyAlgorithm = System.getProperty("ssl.KeyManagerFactory.algorithm");
    if (keyAlgorithm == null) {
        keyAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
    }/*  w w  w.  ja v  a  2 s.  c om*/
    String keyStoreType = System.getProperty("javax.net.ssl.keyStoreType");
    if (keyStoreType == null) {
        keyStoreType = KeyStore.getDefaultType();
    }
    if ("none".equalsIgnoreCase(keyStoreType)) {
        keyManagerFactory = KeyManagerFactory.getInstance(keyAlgorithm);
    } else {
        final String keyStoreFileName = System.getProperty("javax.net.ssl.keyStore");
        if (keyStoreFileName != null) {
            File keyStoreFile = new File(keyStoreFileName);
            keyManagerFactory = KeyManagerFactory.getInstance(keyAlgorithm);
            String keyStoreProvider = System.getProperty("javax.net.ssl.keyStoreProvider");
            KeyStore keyStore;
            if (keyStoreProvider != null) {
                keyStore = KeyStore.getInstance(keyStoreType, keyStoreProvider);
            } else {
                keyStore = KeyStore.getInstance(keyStoreType);
            }
            String password = System.getProperty("javax.net.ssl.keyStorePassword");
            try (FileInputStream in = new FileInputStream(keyStoreFile)) {
                keyStore.load(in, password != null ? password.toCharArray() : null);
            }
            keyManagerFactory.init(keyStore, password != null ? password.toCharArray() : null);
        } else {
            return null;
        }
    }

    return keyManagerFactory.getKeyManagers();
}

From source file:li.klass.fhem.fhem.FHEMWEBConnection.java

private DefaultHttpClient createNewHTTPClient(int connectionTimeout, int socketTimeout) {
    try {//ww w  .j a v a2  s. co  m
        KeyStore trustStore;
        SSLSocketFactory socketFactory;

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

        socketFactory = new CustomSSLSocketFactory(trustStore);
        socketFactory.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, connectionTimeout);
        HttpConnectionParams.setSoTimeout(params, socketTimeout);

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

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

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

From source file:net.shirayu.android.WlanLogin.MyHttpClient.java

public static KeyStore loadKeyStore(Context context) throws KeyStoreException, NoSuchAlgorithmException,
        CertificateException, FileNotFoundException, IOException, NoSuchProviderException {
    /*/* w  w w. j  a va 2 s .c  o  m*/
     * Original implementation.
    I refer the following sites about the default keystore.
    http://wiki.livedoor.jp/syo1976/d/javassl
    http://d.hatena.ne.jp/Kazzz/20110319/p1
     */
    KeyStore certstore;
    if (Integer.valueOf(Build.VERSION.SDK) >= 14) {
        // load from unified key store
        certstore = KeyStore.getInstance("AndroidCAStore");
        certstore.load(null, null);
    } else {
        certstore = KeyStore.getInstance(KeyStore.getDefaultType());
        certstore.load(new FileInputStream(System.getProperty("javax.net.ssl.trustStore")), null); //load default keystore
    }

    //load self_signed_certificate?
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    final Boolean use_self_signed_certificate = sharedPreferences.getBoolean("use_self_signed_certificate",
            false);
    if (use_self_signed_certificate) {
        final Boolean use_folder = sharedPreferences.getBoolean("use_self_signed_certificate_folder", false);
        final String filename = sharedPreferences.getString("self_signed_certificate_path", "//");
        File myfile = new File(filename);

        if (use_folder) {
            for (File file : new File(myfile.getParent()).listFiles()) {
                if (file.isDirectory())
                    continue;
                FileInputStream stream = new FileInputStream(file);
                X509Certificate cert = MyHttpClient.readPem(stream);
                certstore.setCertificateEntry(file.getName(), cert);
            }
        } else {
            FileInputStream stream = new FileInputStream(myfile);
            X509Certificate cert = MyHttpClient.readPem(stream);
            certstore.setCertificateEntry(myfile.getName(), cert);
        }
        ;
    }
    ;

    return certstore;
}