Example usage for javax.net.ssl KeyManagerFactory getDefaultAlgorithm

List of usage examples for javax.net.ssl KeyManagerFactory getDefaultAlgorithm

Introduction

In this page you can find the example usage for javax.net.ssl KeyManagerFactory getDefaultAlgorithm.

Prototype

public static final String getDefaultAlgorithm() 

Source Link

Document

Obtains the default KeyManagerFactory algorithm name.

Usage

From source file:org.miloss.fgsms.bueller.AuthSSLProtocolSocketFactory.java

private static TrustManager[] createTrustManagers(final KeyStore keystore)
        throws KeyStoreException, NoSuchAlgorithmException {
    if (keystore == null) {
        throw new IllegalArgumentException("Keystore may not be null");
    }// w ww . j av  a2s  .  c  o m
    LOG.debug("Initializing trust manager");
    String alg = KeyManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory fac = TrustManagerFactory.getInstance(alg);
    fac.init(keystore);
    return fac.getTrustManagers();
    /*
    TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(
    TrustManagerFactory.getDefaultAlgorithm());
    tmfactory.init(keystore);
    TrustManager[] trustmanagers = tmfactory.getTrustManagers();
    for (int i = 0; i < trustmanagers.length; i++) {
    if (trustmanagers[i] instanceof X509TrustManager) {
        trustmanagers[i] = new AuthSSLX509TrustManager(
            (X509TrustManager)trustmanagers[i]); 
    }
    }
    return trustmanagers; */
}

From source file:org.opcfoundation.ua.transport.https.HttpsSettings.java

/**
 * Set keystore as the key manager for a https application.   
 *  //from  w  w  w. j  a va2 s . c o  m
 * @param keystore
 * @param password
 * @throws NoSuchAlgorithmException
 * @throws UnrecoverableKeyException
 * @throws KeyStoreException
 */
public void setKeyStore(KeyStore keystore, String password) throws ServiceResultException {
    try {
        KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmfactory.init(keystore, password.toCharArray());
        KeyManager kms[] = kmfactory.getKeyManagers();
        keyManager = kms.length == 0 ? null : (X509KeyManager) kms[0];
    } catch (NoSuchAlgorithmException e) {
        throw new ServiceResultException(e);
    } catch (UnrecoverableKeyException e) {
        throw new ServiceResultException(e);
    } catch (KeyStoreException e) {
        throw new ServiceResultException(e);
    }
}

From source file:davmail.util.ClientCertificateTest.java

private SSLContext createSSLContext()
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyManagementException,
        KeyStoreException, IOException, CertificateException, UnrecoverableKeyException {
    // PKCS11 client certificate settings
    String pkcs11Library = Settings.getProperty("davmail.ssl.pkcs11Library");

    String clientKeystoreType = Settings.getProperty("davmail.ssl.clientKeystoreType");
    // set default keystore type
    if (clientKeystoreType == null || clientKeystoreType.length() == 0) {
        clientKeystoreType = "PKCS11";
    }//ww  w.  ja  v  a  2  s. c om

    if (pkcs11Library != null && pkcs11Library.length() > 0 && "PKCS11".equals(clientKeystoreType)) {
        StringBuilder pkcs11Buffer = new StringBuilder();
        pkcs11Buffer.append("name=DavMail\n");
        pkcs11Buffer.append("library=").append(pkcs11Library).append('\n');
        String pkcs11Config = Settings.getProperty("davmail.ssl.pkcs11Config");
        if (pkcs11Config != null && pkcs11Config.length() > 0) {
            pkcs11Buffer.append(pkcs11Config).append('\n');
        }
        SunPKCS11ProviderHandler.registerProvider(pkcs11Buffer.toString());
    }
    String algorithm = KeyManagerFactory.getDefaultAlgorithm();
    if ("SunX509".equals(algorithm)) {
        algorithm = "NewSunX509";
    } else if ("IbmX509".equals(algorithm)) {
        algorithm = "NewIbmX509";
    }
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm);

    ArrayList<KeyStore.Builder> keyStoreBuilders = new ArrayList<KeyStore.Builder>();
    // PKCS11 (smartcard) keystore with password callback
    KeyStore.Builder scBuilder = KeyStore.Builder.newInstance("PKCS11", null, getProtectionParameter(null));
    //keyStoreBuilders.add(scBuilder);

    String clientKeystoreFile = Settings.getProperty("davmail.ssl.clientKeystoreFile");
    String clientKeystorePass = Settings.getProperty("davmail.ssl.clientKeystorePass");
    if (clientKeystoreFile != null && clientKeystoreFile.length() > 0
            && ("PKCS12".equals(clientKeystoreType) || "JKS".equals(clientKeystoreType))) {
        // PKCS12 file based keystore
        KeyStore.Builder fsBuilder = KeyStore.Builder.newInstance(clientKeystoreType, null,
                new File(clientKeystoreFile), getProtectionParameter(clientKeystorePass));
        keyStoreBuilders.add(fsBuilder);
    }
    System.setProperty("javax.net.debug", "ssl,handshake");
    //try {
    Provider sunMSCAPI = new sun.security.mscapi.SunMSCAPI();
    //Security.insertProviderAt(sunMSCAPI, 1);
    KeyStore keyStore = KeyStore.getInstance("Windows-MY", sunMSCAPI);

    keyStore.load(null, null);

    keyStoreBuilders.add(KeyStore.Builder.newInstance(keyStore, new KeyStore.PasswordProtection(null)));

    /*} catch (IOException e) {
    e.printStackTrace();
    } catch (CertificateException e) {
    e.printStackTrace();
    }*/

    ManagerFactoryParameters keyStoreBuilderParameters = new KeyStoreBuilderParameters(keyStoreBuilders);
    keyManagerFactory.init(keyStoreBuilderParameters);
    //keyManagerFactory.init(keyStore, null);

    // Get a list of key managers
    KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();

    // Walk through the key managers and replace all X509 Key Managers with
    // a specialized wrapped DavMail X509 Key Manager
    for (int i = 0; i < keyManagers.length; i++) {
        KeyManager keyManager = keyManagers[i];
        if (keyManager instanceof X509KeyManager) {
            keyManagers[i] = new DavMailX509KeyManager((X509KeyManager) keyManager);
        }
    }

    //keyManagers = new KeyManager[]{new DavMailX509KeyManager(new X509KeyManagerImpl())}

    SSLContext context = SSLContext.getInstance("TLS");
    context.init(keyManagers, new TrustManager[] { new DavGatewayX509TrustManager() }, null);
    return context;
}

From source file:org.eclipse.mylyn.internal.commons.net.PollingSslProtocolSocketFactory.java

private KeyManager[] openKeyStore(String type) throws KeyStoreException, IOException, NoSuchAlgorithmException,
        CertificateException, FileNotFoundException, UnrecoverableKeyException {
    KeyStore keyStore = KeyStore.getInstance(type);
    char[] password = keyStorePassword.toCharArray();
    keyStore.load(new FileInputStream(keyStoreFileName), password);
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, password);
    return keyManagerFactory.getKeyManagers();
}

From source file:org.jenkinsci.remoting.engine.HandlerLoopbackLoadStress.java

public HandlerLoopbackLoadStress(Config config)
        throws IOException, NoSuchAlgorithmException, CertificateException, KeyStoreException,
        UnrecoverableKeyException, KeyManagementException, OperatorCreationException {
    this.config = config;
    KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
    gen.initialize(2048); // maximum supported by JVM with export restrictions
    keyPair = gen.generateKeyPair();//from www . j  a v a  2  s .  c o m

    Date now = new Date();
    Date firstDate = new Date(now.getTime() + TimeUnit.DAYS.toMillis(10));
    Date lastDate = new Date(now.getTime() + TimeUnit.DAYS.toMillis(-10));

    SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo
            .getInstance(keyPair.getPublic().getEncoded());

    X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
    X500Name subject = nameBuilder.addRDN(BCStyle.CN, getClass().getSimpleName()).addRDN(BCStyle.C, "US")
            .build();

    X509v3CertificateBuilder certGen = new X509v3CertificateBuilder(subject, BigInteger.ONE, firstDate,
            lastDate, subject, subjectPublicKeyInfo);

    JcaX509ExtensionUtils instance = new JcaX509ExtensionUtils();

    certGen.addExtension(X509Extension.subjectKeyIdentifier, false,
            instance.createSubjectKeyIdentifier(subjectPublicKeyInfo));

    ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BOUNCY_CASTLE_PROVIDER)
            .build(keyPair.getPrivate());

    certificate = new JcaX509CertificateConverter().setProvider(BOUNCY_CASTLE_PROVIDER)
            .getCertificate(certGen.build(signer));

    char[] password = "password".toCharArray();

    KeyStore store = KeyStore.getInstance("jks");
    store.load(null, password);
    store.setKeyEntry("alias", keyPair.getPrivate(), password, new Certificate[] { certificate });

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(store, password);

    context = SSLContext.getInstance("TLS");
    context.init(kmf.getKeyManagers(), new TrustManager[] { new BlindTrustX509ExtendedTrustManager() }, null);

    mainHub = IOHub.create(executorService);
    // on windows there is a bug whereby you cannot mix ServerSockets and Sockets on the same selector
    acceptorHub = File.pathSeparatorChar == 59 ? IOHub.create(executorService) : mainHub;
    legacyHub = new NioChannelHub(executorService);
    executorService.submit(legacyHub);
    serverSocketChannel = ServerSocketChannel.open();

    JnlpProtocolHandler handler = null;
    for (JnlpProtocolHandler h : new JnlpProtocolHandlerFactory(executorService).withNioChannelHub(legacyHub)
            .withIOHub(mainHub).withSSLContext(context).withPreferNonBlockingIO(!config.bio)
            .withClientDatabase(new JnlpClientDatabase() {
                @Override
                public boolean exists(String clientName) {
                    return true;
                }

                @Override
                public String getSecretOf(@Nonnull String clientName) {
                    return secretFor(clientName);
                }
            }).withSSLClientAuthRequired(false).handlers()) {
        if (config.name.equals(h.getName())) {
            handler = h;
            break;
        }
    }
    if (handler == null) {
        throw new RuntimeException("Unknown handler: " + config.name);
    }
    this.handler = handler;

    acceptor = new Acceptor(serverSocketChannel);
    runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
    _getProcessCpuTime = _getProcessCpuTime(operatingSystemMXBean);
    garbageCollectorMXBeans = new ArrayList<GarbageCollectorMXBean>(
            ManagementFactory.getGarbageCollectorMXBeans());
    Collections.sort(garbageCollectorMXBeans, new Comparator<GarbageCollectorMXBean>() {
        @Override
        public int compare(GarbageCollectorMXBean o1, GarbageCollectorMXBean o2) {
            return o1.getName().compareTo(o2.getName());
        }
    });
    stats = new Stats();
}

From source file:com.android.beyondemail.SSLSocketFactory.java

private static KeyManager[] createKeyManagers(final KeyStore keystore, final String password)
        throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
    if (keystore == null) {
        throw new IllegalArgumentException("Keystore may not be null");
    }//from w  w  w .ja va 2  s  . c  om
    KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmfactory.init(keystore, password != null ? password.toCharArray() : null);
    return kmfactory.getKeyManagers();
}

From source file:org.apache.jmeter.util.JsseSSLManager.java

private SSLContext createContext() throws GeneralSecurityException {
    SSLContext context;//from   w  ww  . j  av  a2  s  .co  m
    if (pro != null) {
        context = SSLContext.getInstance(DEFAULT_SSL_PROTOCOL, pro); // $NON-NLS-1$
    } else {
        context = SSLContext.getInstance(DEFAULT_SSL_PROTOCOL); // $NON-NLS-1$
    }
    KeyManagerFactory managerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    JmeterKeyStore keys = this.getKeyStore();
    managerFactory.init(null, defaultpw == null ? new char[] {} : defaultpw.toCharArray());
    KeyManager[] managers = managerFactory.getKeyManagers();
    KeyManager[] newManagers = new KeyManager[managers.length];

    log.debug(keys.getClass().toString());

    // Now wrap the default managers with our key manager
    for (int i = 0; i < managers.length; i++) {
        if (managers[i] instanceof X509KeyManager) {
            X509KeyManager manager = (X509KeyManager) managers[i];
            newManagers[i] = new WrappedX509KeyManager(manager, keys);
        } else {
            newManagers[i] = managers[i];
        }
    }

    // Get the default trust managers
    TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmfactory.init(this.getTrustStore());

    // Wrap the defaults in our custom trust manager
    TrustManager[] trustmanagers = tmfactory.getTrustManagers();
    for (int i = 0; i < trustmanagers.length; i++) {
        if (trustmanagers[i] instanceof X509TrustManager) {
            trustmanagers[i] = new CustomX509TrustManager((X509TrustManager) trustmanagers[i]);
        }
    }
    context.init(newManagers, trustmanagers, this.rand);
    if (log.isDebugEnabled()) {
        String[] dCiphers = context.getSocketFactory().getDefaultCipherSuites();
        String[] sCiphers = context.getSocketFactory().getSupportedCipherSuites();
        int len = (dCiphers.length > sCiphers.length) ? dCiphers.length : sCiphers.length;
        for (int i = 0; i < len; i++) {
            if (i < dCiphers.length) {
                log.debug("Default Cipher: " + dCiphers[i]);
            }
            if (i < sCiphers.length) {
                log.debug("Supported Cipher: " + sCiphers[i]);
            }
        }
    }
    return context;
}

From source file:org.codice.ddf.spatial.ogc.catalog.common.TestTrustedRemoteSource.java

private TLSClientParameters getTLSParameters(KeyStore keyStore, String keystorePassword, KeyStore trustStore) {
    TLSClientParameters tlsParams = new TLSClientParameters();
    try {//from w ww . j  a v a  2  s  . c o  m
        TrustManagerFactory trustFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustFactory.init(trustStore);
        TrustManager[] tm = trustFactory.getTrustManagers();
        tlsParams.setTrustManagers(tm);

        KeyManagerFactory keyFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyFactory.init(keyStore, keystorePassword.toCharArray());
        KeyManager[] km = keyFactory.getKeyManagers();
        tlsParams.setKeyManagers(km);
    } catch (Exception e) {
        LOGGER.warn("Could not load keystores, may be an error with the filesystem", e);
    }

    FiltersType filter = new FiltersType();
    filter.getInclude().addAll(SecuritySettingsService.SSL_ALLOWED_ALGORITHMS);
    filter.getExclude().addAll(SecuritySettingsService.SSL_DISALLOWED_ALGORITHMS);
    tlsParams.setCipherSuitesFilter(filter);

    return tlsParams;
}

From source file:it.greenvulcano.gvesb.http.ssl.AuthSSLProtocolSocketFactory.java

private static KeyManager[] createKeyManagers(final KeyStore keystore, final String password)
        throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
    if (keystore == null) {
        throw new IllegalArgumentException("Keystore may not be null");
    }/*from ww w  . j  av  a2  s . co m*/
    logger.debug("Initializing key manager");
    KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmfactory.init(keystore, password != null ? password.toCharArray() : null);
    return kmfactory.getKeyManagers();
}

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

/**
 * {@inheritDoc}/*from   w  ww. ja  va 2  s.  c o m*/
 */
@Override
public KeyManager[] createKeyManagers() {
    KeyInfoManager keyInfoManager = null;

    try {
        keyInfoManager = getKeyInfoManager(getKeyMetaDataFileLocation());
        KeyStore ks = loadKeyStore(keyStoreParameters, keyInfoManager);

        logger.debug("Initializing key managers");
        KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());

        String keyStorePassword = keyInfoManager.getKeyStorePassword();
        kmfactory.init(ks, keyStorePassword != null ? keyStorePassword.toCharArray() : null);
        return kmfactory.getKeyManagers();
    } catch (Throwable e) {
        throw new AlfrescoRuntimeException("Unable to create key manager", e);
    } finally {
        if (keyInfoManager != null) {
            keyInfoManager.clear();
        }
    }
}