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.jodconverter.office.OnlineOfficeManagerPoolEntry.java

private KeyStore loadStore(final String store, final String storePassword, final String storeType,
        final String storeProvider) throws NoSuchAlgorithmException, CertificateException, IOException,
        KeyStoreException, NoSuchProviderException {

    if (store != null) {
        Validate.notNull(storePassword, "The password of store {0} must not be null", store);

        KeyStore keyStore;//w  w  w. jav  a  2 s. c o  m

        final String type = storeType == null ? KeyStore.getDefaultType() : storeType;
        if (storeProvider == null) {
            keyStore = KeyStore.getInstance(type);
        } else {
            keyStore = KeyStore.getInstance(type, storeProvider);
        }

        try (FileInputStream instream = new FileInputStream(getFile(store))) {
            keyStore.load(instream, storePassword.toCharArray());
        }

        return keyStore;
    }
    return null;
}

From source file:org.exoplatform.services.videocall.AuthService.java

protected static TrustManager[] getTrustManagers(InputStream trustStoreFile, String trustStorePassword)
        throws Exception {
    CertificateFactory certificateFactory = null;
    try {/*from  w w w  . j  a va 2 s  .  c om*/
        certificateFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Could not initialize the certificate " + e.getMessage());
        }
    }

    Certificate caCert = null;
    try {
        caCert = certificateFactory.generateCertificate(trustStoreFile);
    } catch (CertificateException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Bad key or certificate in " + trustStoreFile, e.getMessage());
        }
    }

    KeyStore trustStore = null;
    try {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
    } catch (KeyStoreException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Java implementation cannot manipulate " + KeyStore.getDefaultType() + " keystores");
        }
    } catch (NoSuchAlgorithmException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Could not initialize truststore ", e);
        }
    } catch (CertificateException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Could not initialize truststore ", e);
        }
    } catch (IOException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Could not initialize truststore ", e);
        }
    }

    try {
        trustStore.setCertificateEntry("CA", caCert);
    } catch (KeyStoreException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error(trustStoreFile + " cannot be used as a CA", e);
        }
    }

    TrustManagerFactory tmf = null;
    try {
        tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trustStore);
    } catch (NoSuchAlgorithmException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Java implementation cannot manipulate " + KeyStore.getDefaultType() + " trusts", e);
        }
    } catch (KeyStoreException e) {
        LOG.error("Java implementation cannot manipulate " + KeyStore.getDefaultType() + " trusts", e);
    }
    return tmf.getTrustManagers();
}

From source file:org.mule.transport.ldap.util.DSManager.java

public synchronized void start(final boolean allowAnon) throws Exception {
    if (running) {

        logger.debug("start() called while already running");

        if (checkSocketNotConnected()) {
            logger.debug("start() forced");
        } else {// www  .  j a v a 2 s  .  c  o m
            logger.debug("DS is already running, stop it, then start it.");

            try {
                stop();

            } catch (final Exception e) {
                // TODO: handle exception
            }

            // throw new IllegalStateException("DS already running on port "
            // + port);
        }

    }

    logger.debug("DS is starting ...");

    port = 10389;

    directoryService = new DefaultDirectoryService();
    directoryService.setShutdownHookEnabled(false);
    // directoryService.getChangeLog().setEnabled(true);
    directoryService.setAllowAnonymousAccess(allowAnon);

    socketAcceptor = new SocketAcceptor(null);
    ldapService = new LdapService();
    ldapService.setSocketAcceptor(socketAcceptor);
    ldapService.setDirectoryService(directoryService);
    ldapService.setIpPort(port);
    // ldapService.setIpAddress("gkar.kerb.de");

    // ldapService.setAccessControlEnabled(false);
    // ldapService.setShutdownHookEnabled(false);
    ldapService.setAllowAnonymousAccess(allowAnon);

    // ldapService.getLdapsConfiguration().setIpPort(10636);
    // ldapService.getLdapsConfiguration().setEnabled(true);
    // ldapService.getLdapsConfiguration().setLdapsCertificateFile(new
    // File("src/test/resources/ldaps-server-cert.jks"));
    // ldapService.getLdapsConfiguration().setIpPort(10636);

    setupSaslMechanisms(ldapService);

    // S
    ldapSService = new LdapService();
    ldapSService.setSocketAcceptor(socketAcceptor);
    ldapSService.setDirectoryService(directoryService);
    ldapSService.setIpPort(10636);
    ldapSService.setEnableLdaps(true);

    setupSaslMechanisms(ldapSService);

    // ldapSService.setConfidentialityRequired(true);
    ldapSService.setConfidentialityRequired(true);
    // ldapService.setIpAddress("gkar.kerb.de");

    // ldapService.setAccessControlEnabled(false);
    // ldapService.setShutdownHookEnabled(false);
    ldapSService.setAllowAnonymousAccess(allowAnon);

    // ldapService.getLdapsConfiguration().setIpPort(10636);
    // ldapService.getLdapsConfiguration().setEnabled(true);
    // ldapService.getLdapsConfiguration().setLdapsCertificateFile(new
    // File("src/test/resources/ldaps-server-cert.jks"));
    // ldapService.getLdapsConfiguration().setIpPort(10636);

    setupSaslMechanisms(ldapSService);

    doDelete(directoryService.getWorkingDirectory());

    directoryService.startup();

    // java.security.cert.X509Certificate cert =
    // TlsKeyGenerator.getCertificate(directoryService.getAdminSession().lookup(new
    // LdapDN("uid=admin,ou=system")).getOriginalEntry());

    final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(new FileInputStream("src/test/resources/truststore_2.jks"), "changeit".toCharArray());

    // java.security.cert.X509Certificate testcert =
    // (java.security.cert.X509Certificate) ks.getCertificate("test");
    // logger.debug(testcert);
    // directoryService.getAdminSession().lookup(new
    // LdapDN("uid=admin,ou=system")).getOriginalEntry().put("userCertificate",testcert.getEncoded());

    // logger.debug("type: "+testcert.getType());
    final java.security.cert.X509Certificate cert = TlsKeyGenerator.getCertificate(
            directoryService.getAdminSession().lookup(new LdapDN("uid=admin,ou=system")).getOriginalEntry());

    ks.setCertificateEntry("apachetmp", cert);

    final File tmpKs = new File("target/truststore_tmp.jks");
    if (tmpKs.exists()) {
        boolean del = tmpKs.delete();

        if (!del) {
            logger.error("Unable to delete " + tmpKs.getAbsolutePath());
            // throw new Exception("Unable to delete
            // "+tmpKs.getAbsolutePath());
        }
    }

    ks.store(new FileOutputStream("target/truststore_tmp.jks"), "changeit".toCharArray());

    logger.debug(cert);

    // TODO shouldn't this be before calling configureLdapServer() ???
    ldapService.addExtendedOperationHandler(new StartTlsHandler());
    ldapService.addExtendedOperationHandler(new StoredProcedureExtendedOperationHandler());

    ldapService.start();

    ldapSService.addExtendedOperationHandler(new StartTlsHandler());
    // ldapSService.add( new LdapsInitializer() );
    ldapSService.addExtendedOperationHandler(new StoredProcedureExtendedOperationHandler());

    ldapSService.start();

    // dn: uid=admin,ou=system
    setContexts(ServerDNConstants.ADMIN_SYSTEM_DN, "secret");

    setUpPartition();

    importLdif(IOUtils.getResourceAsStream("examplecom.ldif", this.getClass()));

    final Attributes attrs = new BasicAttributes();
    attrs.put(new BasicAttribute("userCertificate", ""));

    // sysRoot.modifyAttributes("uid=admin",LdapContext.REPLACE_ATTRIBUTE,attrs);
    logger.debug(rootDSE.getAuthenticatedPrincipal());
    logger.debug(rootDSE.getAuthenticationLevel());
    logger.debug(rootDSE.getEffectivePrincipal());
    logger.debug(rootDSE.toString());

    running = true;

    logger.debug("DS now started!");
}

From source file:io.atomix.cluster.messaging.impl.NettyMessagingService.java

private boolean loadKeyStores() {
    // Maintain a local copy of the trust and key managers in case anything goes wrong
    TrustManagerFactory tmf;/*from  w w w  .  j  ava 2s.c  o  m*/
    KeyManagerFactory kmf;
    try {
        String ksLocation = System.getProperty("javax.net.ssl.keyStore", DEFAULT_KS_FILE.toString());
        String tsLocation = System.getProperty("javax.net.ssl.trustStore", DEFAULT_KS_FILE.toString());
        char[] ksPwd = System.getProperty("javax.net.ssl.keyStorePassword", DEFAULT_KS_PASSWORD).toCharArray();
        char[] tsPwd = System.getProperty("javax.net.ssl.trustStorePassword", DEFAULT_KS_PASSWORD)
                .toCharArray();

        tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        KeyStore ts = KeyStore.getInstance(KeyStore.getDefaultType());
        try (FileInputStream fileInputStream = new FileInputStream(tsLocation)) {
            ts.load(fileInputStream, tsPwd);
        }
        tmf.init(ts);

        kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        try (FileInputStream fileInputStream = new FileInputStream(ksLocation)) {
            ks.load(fileInputStream, ksPwd);
        }
        kmf.init(ks, ksPwd);
        if (log.isInfoEnabled()) {
            logKeyStore(ks, ksLocation, ksPwd);
        }
    } catch (FileNotFoundException e) {
        log.warn("Disabling TLS for intra-cluster messaging; Could not load cluster key store: {}",
                e.getMessage());
        return TLS_DISABLED;
    } catch (Exception e) {
        //TODO we might want to catch exceptions more specifically
        log.error("Error loading key store; disabling TLS for intra-cluster messaging", e);
        return TLS_DISABLED;
    }
    this.trustManager = tmf;
    this.keyManager = kmf;
    return TLS_ENABLED;
}

From source file:org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils.java

/**
 * This method will remove certificate from the trust store which matches the given alias.
 *
 * @param alias : The alias which the certificate should be deleted.
 * @return : ResponseCode based on the execution.
 * <p>/*from   w  ww. j  a v  a 2 s  . c o m*/
 * Response Codes
 * SUCCESS : If the certificate is deleted successfully.
 * INTERNAL_SERVER_ERROR : If any exception occurred.
 * CERTIFICATE_NOT_FOUND : If the Alias is not found in the key store.
 */
public ResponseCode removeCertificateFromTrustStore(String alias) {

    boolean isExists; //Check for the existence of the certificate in trust store.
    try {
        File trustStoreFile = new File(TRUST_STORE);
        localTrustStoreStream = new FileInputStream(trustStoreFile);
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(localTrustStoreStream, TRUST_STORE_PASSWORD);

        if (trustStore.containsAlias(alias)) {
            trustStore.deleteEntry(alias);
            isExists = true;
        } else {
            isExists = false;
            if (log.isDebugEnabled()) {
                log.debug("Certificate for alias '" + alias + "' not found in the trust store.");
            }
        }

        fileOutputStream = new FileOutputStream(trustStoreFile);
        trustStore.store(fileOutputStream, TRUST_STORE_PASSWORD);
        responseCode = isExists ? ResponseCode.SUCCESS : ResponseCode.CERTIFICATE_NOT_FOUND;
    } catch (IOException e) {
        log.error("Error in loading the certificate.", e);
        responseCode = ResponseCode.INTERNAL_SERVER_ERROR;
    } catch (CertificateException e) {
        log.error("Error loading certificate.", e);
        responseCode = ResponseCode.INTERNAL_SERVER_ERROR;
    } catch (NoSuchAlgorithmException e) {
        log.error("Could not find the algorithm to load the certificate.", e);
        responseCode = ResponseCode.INTERNAL_SERVER_ERROR;
    } catch (KeyStoreException e) {
        log.error("Error reading certificate contents.", e);
        responseCode = ResponseCode.INTERNAL_SERVER_ERROR;
    } finally {
        closeStreams(localTrustStoreStream, fileOutputStream);
    }
    return responseCode;
}

From source file:de.fun2code.google.cloudprint.push.PushReceiver.java

/**
 * Sets up the SSL socket for use with XMPP.
 * /*from w ww . ja v a  2s  .c om*/
 * @param socket
 *            the socket to do TLS over.
 * @return   The SSL Socket.
 * @throws IOException
 */
public static SSLSocket setupSSLSocket(Socket socket) throws NoSuchAlgorithmException, KeyManagementException,
        KeyStoreException, UnrecoverableKeyException, IOException {
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    TrustManagerFactory tfactory = TrustManagerFactory.getInstance("SunPKIX");
    tfactory.init(keyStore);
    SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
    SSLSocket sslsocket = (SSLSocket) factory.createSocket(socket, socket.getInetAddress().getHostAddress(),
            socket.getPort(), true);
    sslsocket.setUseClientMode(true);
    return sslsocket;
}

From source file:com.owncloud.android.network.OwnCloudClientUtils.java

/**
 * Returns the local store of reliable server certificates, explicitly accepted by the user.
 * /*from  w w w  .  ja va2 s. co  m*/
 * Returns a KeyStore instance with empty content if the local store was never created.
 * 
 * Loads the store from the storage environment if needed.
 * 
 * @param context                       Android context where the operation is being performed.
 * @return                              KeyStore instance with explicitly-accepted server certificates. 
 * @throws KeyStoreException            When the KeyStore instance could not be created.
 * @throws IOException                  When an existing local trust store could not be loaded.
 * @throws NoSuchAlgorithmException     When the existing local trust store was saved with an unsupported algorithm.
 * @throws CertificateException         When an exception occurred while loading the certificates from the local trust store.
 */
private static KeyStore getKnownServersStore(Context context)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
    if (mKnownServersStore == null) {
        //mKnownServersStore = KeyStore.getInstance("BKS");
        mKnownServersStore = KeyStore.getInstance(KeyStore.getDefaultType());
        File localTrustStoreFile = new File(context.getFilesDir(), LOCAL_TRUSTSTORE_FILENAME);
        Log_OC.d(TAG, "Searching known-servers store at " + localTrustStoreFile.getAbsolutePath());
        if (localTrustStoreFile.exists()) {
            InputStream in = new FileInputStream(localTrustStoreFile);
            try {
                mKnownServersStore.load(in, LOCAL_TRUSTSTORE_PASSWORD.toCharArray());
            } finally {
                in.close();
            }
        } else {
            mKnownServersStore.load(null, LOCAL_TRUSTSTORE_PASSWORD.toCharArray()); // necessary to initialize an empty KeyStore instance
        }
    }
    return mKnownServersStore;
}

From source file:com.github.tomakehurst.wiremock.HttpsAcceptanceTest.java

static KeyStore readKeyStore(String path, String password)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    FileInputStream instream = new FileInputStream(path);
    try {/*from   w  w  w .j a  va  2  s  . com*/
        trustStore.load(instream, password.toCharArray());
    } finally {
        instream.close();
    }
    return trustStore;
}

From source file:com.eastedge.readnovel.weibo.net.Utility.java

public static HttpClient getNewHttpClient(Context context) {
    try {// w ww . j  av a 2 s.  co 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, Utility.SET_CONNECTION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, Utility.SET_SOCKET_TIMEOUT);
        HttpClient client = new DefaultHttpClient(ccm, params);
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        if (!wifiManager.isWifiEnabled()) {
            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();
    }
}