Java Code Examples for javax.net.ssl.KeyManagerFactory#getDefaultAlgorithm()

The following examples show how to use javax.net.ssl.KeyManagerFactory#getDefaultAlgorithm() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestInsecureQueryRunner.java    From presto with Apache License 2.0 6 votes vote down vote up
private SSLContext buildTestSslContext()
        throws Exception
{
    // Load self-signed certificate
    char[] serverKeyStorePassword = "insecure-ssl-test".toCharArray();
    KeyStore serverKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    try (InputStream in = getResource(getClass(), "/insecure-ssl-test.jks").openStream()) {
        serverKeyStore.load(in, serverKeyStorePassword);
    }

    String kmfAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(kmfAlgorithm);
    kmf.init(serverKeyStore, serverKeyStorePassword);

    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(kmfAlgorithm);
    trustManagerFactory.init(serverKeyStore);
    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(kmf.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
    return sslContext;
}
 
Example 2
Source File: AuthSSLProtocolSocketFactoryForJsse10x.java    From iaf with Apache License 2.0 6 votes vote down vote up
private static KeyManager[] createKeyManagers(final KeyStore keystore, final String password, String algorithm)
    throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException 
{
    if (keystore == null) {
        throw new IllegalArgumentException("Keystore may not be null");
    }
    log.debug("Initializing key manager");
    if (StringUtils.isEmpty(algorithm)) {
    	algorithm=KeyManagerFactory.getDefaultAlgorithm();
    	log.debug("using default KeyManager algorithm ["+algorithm+"]");
    } else {
    	log.debug("using configured KeyManager algorithm ["+algorithm+"]");
    }
    KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(algorithm);
    kmfactory.init(keystore, password != null ? password.toCharArray(): null);
    return kmfactory.getKeyManagers(); 
}
 
Example 3
Source File: AuthSSLProtocolSocketFactory.java    From iaf with Apache License 2.0 6 votes vote down vote up
private static KeyManager[] createKeyManagers(final KeyStore keystore, final String password, String algorithm)
    throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException
{
    if (keystore == null) {
        throw new IllegalArgumentException("Keystore may not be null");
    }
    log.debug("Initializing key manager");
    if (StringUtils.isEmpty(algorithm)) {
    	algorithm=KeyManagerFactory.getDefaultAlgorithm();
    	log.debug("using default KeyManager algorithm ["+algorithm+"]");
    } else {
    	log.debug("using configured KeyManager algorithm ["+algorithm+"]");
    }
    KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(algorithm);
    kmfactory.init(keystore, password != null ? password.toCharArray(): null);
    return kmfactory.getKeyManagers(); 
}
 
Example 4
Source File: HTTPSConduitTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static KeyManager[] getKeyManagers(KeyStore keyStore, String keyPassword)
    throws GeneralSecurityException,
           IOException {
    // For tests, we just use the default algorithm
    String alg = KeyManagerFactory.getDefaultAlgorithm();

    char[] keyPass = keyPassword != null
                 ? keyPassword.toCharArray()
                 : null;

    // For tests, we just use the default provider.
    KeyManagerFactory fac = KeyManagerFactory.getInstance(alg);

    fac.init(keyStore, keyPass);

    return fac.getKeyManagers();
}
 
Example 5
Source File: KeyStoreUtil.java    From Dream-Catcher with MIT License 6 votes vote down vote up
/**
 * Retrieve the KeyManagers for the specified KeyStore.
 *
 * @param keyStore            the KeyStore to retrieve KeyManagers from
 * @param keyStorePassword    the KeyStore password
 * @param keyManagerAlgorithm key manager algorithm to use, or null to use the system default
 * @param provider            JCA provider to use, or null to use the system default
 * @return KeyManagers for the specified KeyStore
 */
public static KeyManager[] getKeyManagers(KeyStore keyStore, String keyStorePassword, String keyManagerAlgorithm, String provider) {
    if (keyManagerAlgorithm == null) {
        keyManagerAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
    }

    try {
        KeyManagerFactory kmf;
        if (provider == null) {
            kmf = KeyManagerFactory.getInstance(keyManagerAlgorithm);
        } else {
            kmf = KeyManagerFactory.getInstance(keyManagerAlgorithm, provider);
        }

        kmf.init(keyStore, keyStorePassword.toCharArray());

        return kmf.getKeyManagers();
    } catch (NoSuchAlgorithmException | UnrecoverableKeyException | KeyStoreException | NoSuchProviderException e) {
        throw new KeyStoreAccessException("Unable to get KeyManagers for KeyStore", e);
    }
}
 
Example 6
Source File: SSLNettyServerTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private static KeyManager[] getKeyManagers(KeyStore keyStore, String keyPassword)
    throws GeneralSecurityException, IOException {
    String alg = KeyManagerFactory.getDefaultAlgorithm();
    char[] keyPass = keyPassword != null
                 ? keyPassword.toCharArray()
                 : null;
    KeyManagerFactory fac = KeyManagerFactory.getInstance(alg);
    fac.init(keyStore, keyPass);
    return fac.getKeyManagers();
}
 
Example 7
Source File: SSLSocketTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Loads a keystore from a base64-encoded String. Returns the KeyManager[]
 * for the result.
 */
private KeyManager[] getKeyManagers(String keys) throws Exception {
    byte[] bytes = Base64.decode(keys.getBytes());
    InputStream inputStream = new ByteArrayInputStream(bytes);

    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(inputStream, PASSWORD.toCharArray());
    inputStream.close();

    String algorithm = KeyManagerFactory.getDefaultAlgorithm();
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm);
    keyManagerFactory.init(keyStore, PASSWORD.toCharArray());

    return keyManagerFactory.getKeyManagers();
}
 
Example 8
Source File: HttpWebConnectionTruststoreTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
private static KeyManagerFactory createKeyManagerFactory() throws NoSuchAlgorithmException {
    final String algorithm = KeyManagerFactory.getDefaultAlgorithm();
    try {
        return KeyManagerFactory.getInstance(algorithm);
    }
    catch (final NoSuchAlgorithmException e) {
        return KeyManagerFactory.getInstance("SunX509");
    }
}
 
Example 9
Source File: CertificateHelper.java    From LittleProxy-mitm with Apache License 2.0 5 votes vote down vote up
public static KeyManager[] getKeyManagers(KeyStore keyStore,
        Authority authority) throws NoSuchAlgorithmException,
        NoSuchProviderException, UnrecoverableKeyException,
        KeyStoreException {
    String keyManAlg = KeyManagerFactory.getDefaultAlgorithm();
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(keyManAlg
    /* , PROVIDER_NAME */);
    kmf.init(keyStore, authority.password());
    return kmf.getKeyManagers();
}
 
Example 10
Source File: CalculatorTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
private static KeyManager[] getKeyManagers(KeyStore keyStore, String keyPassword) throws GeneralSecurityException, IOException {
    String alg = KeyManagerFactory.getDefaultAlgorithm();
    char[] keyPass = keyPassword != null ? keyPassword.toCharArray() : null;
    KeyManagerFactory fac = KeyManagerFactory.getInstance(alg);
    fac.init(keyStore, keyPass);
    return fac.getKeyManagers();
}
 
Example 11
Source File: Utils.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
public static KeyManager[] getKeyManagers(KeyStore keyStore, String keyPassword)
    throws GeneralSecurityException, IOException {
    // For tests, we just use the default algorithm
    String alg = KeyManagerFactory.getDefaultAlgorithm();
    char[] keyPass = keyPassword != null ? keyPassword.toCharArray() : null;
    // For tests, we just use the default provider.
    KeyManagerFactory fac = KeyManagerFactory.getInstance(alg);
    fac.init(keyStore, keyPass);
    return fac.getKeyManagers();
}
 
Example 12
Source File: AuthSSLConnectionSocket.java    From iaf with Apache License 2.0 5 votes vote down vote up
private static KeyManager[] createKeyManagers(final KeyStore keystore, final String password, String algorithm) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
	if (keystore == null) {
		throw new IllegalArgumentException("Keystore may not be null");
	}
	log.debug("Initializing key manager");
	if (StringUtils.isEmpty(algorithm)) {
		algorithm=KeyManagerFactory.getDefaultAlgorithm();
		log.debug("using default KeyManager algorithm ["+algorithm+"]");
	} else {
		log.debug("using configured KeyManager algorithm ["+algorithm+"]");
	}
	KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(algorithm);
	kmfactory.init(keystore, password != null ? password.toCharArray(): null);
	return kmfactory.getKeyManagers(); 
}
 
Example 13
Source File: SSLNettyClientTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private static KeyManager[] getKeyManagers(KeyStore keyStore, String keyPassword)
    throws GeneralSecurityException, IOException {
    String alg = KeyManagerFactory.getDefaultAlgorithm();
    char[] keyPass = keyPassword != null
                 ? keyPassword.toCharArray()
                 : null;
    KeyManagerFactory fac = KeyManagerFactory.getInstance(alg);
    fac.init(keyStore, keyPass);
    return fac.getKeyManagers();
}
 
Example 14
Source File: KeyStoreConfiguration.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @throws StoreConfigurationException Thrown if this instance cannot load the KeyStore.
 */
public KeyStoreConfiguration(final String location,
                             final PasswordProvider  passwordProvider,
                             final String keyStoreType,
                             final String keyManagerFactoryAlgorithm) throws StoreConfigurationException {
    super(location, passwordProvider, keyStoreType);
    this.keyManagerFactoryAlgorithm = keyManagerFactoryAlgorithm == null ? KeyManagerFactory.getDefaultAlgorithm()
            : keyManagerFactoryAlgorithm;
}
 
Example 15
Source File: HandshakeCompletedEventTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Loads a keystore from a base64-encoded String. Returns the KeyManager[]
 * for the result.
 */
private KeyManager[] getKeyManagers(String keys) throws Exception {
    byte[] bytes = Base64.decode(keys.getBytes());
    InputStream inputStream = new ByteArrayInputStream(bytes);

    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(inputStream, PASSWORD.toCharArray());
    inputStream.close();

    String algorithm = KeyManagerFactory.getDefaultAlgorithm();
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm);
    keyManagerFactory.init(keyStore, PASSWORD.toCharArray());

    return keyManagerFactory.getKeyManagers();
}
 
Example 16
Source File: JdkSslFactory.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * Create {@link SSLContext} by loading keystore and trustsotre
 * One factory only has one SSLContext
 * @param sslConfig the config for setting up the {@link SSLContext}
 * @return SSLContext
 * @throws GeneralSecurityException
 * @throws IOException
 */
private SSLContext createSSLContext(SSLConfig sslConfig) throws GeneralSecurityException, IOException {
  SSLContext sslContext;
  if (!sslConfig.sslContextProvider.isEmpty()) {
    sslContext = SSLContext.getInstance(sslConfig.sslContextProtocol, sslConfig.sslContextProvider);
  } else {
    sslContext = SSLContext.getInstance(sslConfig.sslContextProtocol);
  }

  SecurityStore keystore =
      new SecurityStore(sslConfig.sslKeystoreType, sslConfig.sslKeystorePath, sslConfig.sslKeystorePassword);
  String kmfAlgorithm = sslConfig.sslKeymanagerAlgorithm.isEmpty() ? KeyManagerFactory.getDefaultAlgorithm()
      : sslConfig.sslKeymanagerAlgorithm;
  KeyManagerFactory kmf = KeyManagerFactory.getInstance(kmfAlgorithm);
  KeyStore ks = keystore.load();
  String keyPassword = sslConfig.sslKeyPassword.isEmpty() ? keystore.password : sslConfig.sslKeyPassword;
  kmf.init(ks, keyPassword.toCharArray());
  KeyManager[] keyManagers = kmf.getKeyManagers();

  String tmfAlgorithm = sslConfig.sslTrustmanagerAlgorithm.isEmpty() ? TrustManagerFactory.getDefaultAlgorithm()
      : sslConfig.sslTrustmanagerAlgorithm;
  TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
  KeyStore ts = new SecurityStore(sslConfig.sslTruststoreType, sslConfig.sslTruststorePath,
      sslConfig.sslTruststorePassword).load();
  tmf.init(ts);

  sslContext.init(keyManagers, tmf.getTrustManagers(),
      sslConfig.sslSecureRandomAlgorithm.isEmpty() ? new SecureRandom()
          : SecureRandom.getInstance(sslConfig.sslSecureRandomAlgorithm));
  return sslContext;
}
 
Example 17
Source File: SSLEngineFactory.java    From java-dcp-client with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new {@link SSLEngine} constructed from the config settings.
 *
 * @return a {@link SSLEngine} ready to be used.
 */
public SSLEngine get() {
  try {
    String pass = env.sslKeystorePassword();
    char[] password = pass == null || pass.isEmpty() ? null : pass.toCharArray();

    KeyStore ks = env.sslKeystore();
    if (ks == null) {
      ks = KeyStore.getInstance(KeyStore.getDefaultType());
      String ksFile = env.sslKeystoreFile();
      if (ksFile == null || ksFile.isEmpty()) {
        throw new IllegalArgumentException("Path to Keystore File must not be null or empty.");
      }
      ks.load(new FileInputStream(ksFile), password);
    }
    String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(defaultAlgorithm);
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(defaultAlgorithm);
    kmf.init(ks, password);
    tmf.init(ks);

    SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

    SSLEngine engine = ctx.createSSLEngine();
    engine.setUseClientMode(true);
    return engine;
  } catch (Exception ex) {
    throw new SSLException("Could not create SSLEngine.", ex);
  }
}
 
Example 18
Source File: CertificateHelper.java    From signer with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static KeyManager[] getKeyManagers(KeyStore keyStore, Authority authority)
		throws NoSuchAlgorithmException, NoSuchProviderException, UnrecoverableKeyException, KeyStoreException {
	String keyManAlg = KeyManagerFactory.getDefaultAlgorithm();
	KeyManagerFactory kmf = KeyManagerFactory.getInstance(keyManAlg
	/* , PROVIDER_NAME */);
	kmf.init(keyStore, authority.password());
	return kmf.getKeyManagers();
}
 
Example 19
Source File: DavGatewaySSLProtocolSocketFactory.java    From davmail with GNU General Public License v2.0 4 votes vote down vote up
private SSLContext createSSLContext() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyManagementException, KeyStoreException {
    // 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";
    }

    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<>();
    // 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);
    }
    // Enable native Windows SmartCard access through MSCAPI (no PKCS11 config required)
    if ("MSCAPI".equals(clientKeystoreType)) {
        try {
            Provider provider = (Provider) Class.forName("sun.security.mscapi.SunMSCAPI").newInstance();
            KeyStore keyStore = KeyStore.getInstance("Windows-MY", provider);
            keyStore.load(null, null);
            keyStoreBuilders.add(KeyStore.Builder.newInstance(keyStore, new KeyStore.PasswordProtection(null)));
        } catch (Exception e) {
            // ignore
        }
    }

    ManagerFactoryParameters keyStoreBuilderParameters = new KeyStoreBuilderParameters(keyStoreBuilders);
    keyManagerFactory.init(keyStoreBuilderParameters);

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

    SSLContext context = SSLContext.getInstance("TLS");
    context.init(keyManagers, new TrustManager[]{new DavGatewayX509TrustManager()}, null);
    return context;
}
 
Example 20
Source File: LdapServer.java    From MyVirtualDirectory with Apache License 2.0 4 votes vote down vote up
/**
 * loads the digital certificate either from a keystore file or from the admin entry in DIT
 */
public void loadKeyStore() throws Exception
{
    if ( Strings.isEmpty( keystoreFile ) )
    {
        Provider provider = Security.getProvider( "SUN" );
        LOG.debug( "provider = {}", provider );
        CoreKeyStoreSpi coreKeyStoreSpi = new CoreKeyStoreSpi( getDirectoryService() );
        keyStore = new KeyStore( coreKeyStoreSpi, provider, "JKS" )
        {
        };

        try
        {
            keyStore.load( null, null );
        }
        catch ( Exception e )
        {
            // nothing really happens with this keystore
        }
    }
    else
    {
        keyStore = KeyStore.getInstance( KeyStore.getDefaultType() );
        try ( FileInputStream fis = new FileInputStream( keystoreFile ) )
        {
            keyStore.load( fis, null );
        }

        // Set up key manager factory to use our key store
        String algorithm = Security.getProperty( "ssl.KeyManagerFactory.algorithm" );

        if ( algorithm == null )
        {
            algorithm = KeyManagerFactory.getDefaultAlgorithm();
        }


        keyManagerFactory = KeyManagerFactory.getInstance( algorithm );

        if ( Strings.isEmpty( certificatePassword ) )
        {
            keyManagerFactory.init( keyStore, null );
        }
        else
        {
            keyManagerFactory.init( keyStore, certificatePassword.toCharArray() );
        }
    }
}