Java Code Examples for javax.net.ssl.X509KeyManager

The following are top voted examples for showing how to use javax.net.ssl.X509KeyManager. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: esteidhacker   File: TestCardProvider.java   Source Code and License 10 votes vote down vote up
@Test
@Ignore
public void testCardProvider() throws GeneralSecurityException, CardException {
    DelegatingProvider cp = DelegatingProvider.fromDelegate(CardDelegate.any(false, CONSOLE));
    Assume.assumeNotNull(cp);

    Security.insertProviderAt(cp, 0);
    X509KeyManager km = cp.getKeyManager();

    String alias = km.chooseClientAlias(new String[]{"RSA"}, null, null);
    PrivateKey pk = km.getPrivateKey(alias);
    Signature s = Signature.getInstance("SHA256withRSA");
    s.initSign(pk);
    s.update(HexUtils.hex2bin("311fe3feed16b9cd8df0f8b1517be5cb86048707df4889ba8dc37d4d68866d02"));
    byte[] result = s.sign();
    System.out.println(HexUtils.bin2hex(result));
}
 
Example 2
Project: mobile-store   File: LocalRepoKeyStore.java   Source Code and License 6 votes vote down vote up
private void addToStore(String alias, KeyPair kp, Certificate cert) throws KeyStoreException,
        NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException {
    Certificate[] chain = {
        cert,
    };
    keyStore.setKeyEntry(alias, kp.getPrivate(),
            "".toCharArray(), chain);

    keyStore.store(new FileOutputStream(keyStoreFile), "".toCharArray());

    /*
     * After adding an entry to the keystore we need to create a fresh
     * KeyManager by reinitializing the KeyManagerFactory with the new key
     * store content and then rewrapping the default KeyManager with our own
     */
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());

    keyManagerFactory.init(keyStore, "".toCharArray());
    KeyManager defaultKeyManager = keyManagerFactory.getKeyManagers()[0];
    KeyManager wrappedKeyManager = new KerplappKeyManager((X509KeyManager) defaultKeyManager);
    keyManagers = new KeyManager[] {
        wrappedKeyManager,
    };
}
 
Example 3
Project: tomcat7   File: NioEndpoint.java   Source Code and License 6 votes vote down vote up
public KeyManager[] wrap(KeyManager[] managers) {
    if (managers==null) return null;
    KeyManager[] result = new KeyManager[managers.length];
    for (int i=0; i<result.length; i++) {
        if (managers[i] instanceof X509KeyManager && getKeyAlias()!=null) {
            String keyAlias = getKeyAlias();
            // JKS keystores always convert the alias name to lower case
            if ("jks".equalsIgnoreCase(getKeystoreType())) {
                keyAlias = keyAlias.toLowerCase(Locale.ENGLISH);
            }
            result[i] = new NioX509KeyManager((X509KeyManager) managers[i], keyAlias);
        } else {
            result[i] = managers[i];
        }
    }
    return result;
}
 
Example 4
Project: cas-server-4.2.1   File: FileTrustStoreSslSocketFactory.java   Source Code and License 6 votes vote down vote up
/**
 * Gets the trusted ssl context.
 *
 * @param trustStoreFile the trust store file
 * @param trustStorePassword the trust store password
 * @param trustStoreType the trust store type
 * @return the trusted ssl context
 */
private static SSLContext getTrustedSslContext(final File trustStoreFile, final String trustStorePassword,
                                        final String trustStoreType) {
    try {

        if (!trustStoreFile.exists() || !trustStoreFile.canRead()) {
            throw new FileNotFoundException("Truststore file cannot be located at "
                + trustStoreFile.getCanonicalPath());
        }

        final KeyStore casTrustStore = KeyStore.getInstance(trustStoreType);
        final char[] trustStorePasswordCharArray = trustStorePassword.toCharArray();

        try (final FileInputStream casStream = new FileInputStream(trustStoreFile)) {
            casTrustStore.load(casStream, trustStorePasswordCharArray);
        }

        final String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
        final X509KeyManager customKeyManager = getKeyManager("PKIX", casTrustStore, trustStorePasswordCharArray);
        final X509KeyManager jvmKeyManager = getKeyManager(defaultAlgorithm, null, null);
        final X509TrustManager customTrustManager = getTrustManager("PKIX", casTrustStore);
        final X509TrustManager jvmTrustManager = getTrustManager(defaultAlgorithm, null);

        final KeyManager[] keyManagers = {
                new CompositeX509KeyManager(Arrays.asList(jvmKeyManager, customKeyManager))
        };
        final TrustManager[] trustManagers = {
                new CompositeX509TrustManager(Arrays.asList(jvmTrustManager, customTrustManager))
        };

        final SSLContext context = SSLContexts.custom().useSSL().build();
        context.init(keyManagers, trustManagers, null);
        return context;

    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw new RuntimeException(e);
    }
}
 
Example 5
Project: lams   File: TLSProtocolSocketFactory.java   Source Code and License 6 votes vote down vote up
/**
 * Constructor.
 * 
 * @param keyMgr manager used to retrieve client-cert authentication keys for a given host.
 * @param trustMgr manager used to validate the X.509 credentials of a given host. May be null, in which case
 *          the JSSE default trust manager lookup mechanism is used.
 * @param verifier the hostname verifier used to verify the SSL/TLS's peer's hostname. May be null, in which case
 *          no hostname verification is performed.
 * 
 * @throws IllegalArgumentException thrown if the given key or trust manager can not be used to create the
 *             {@link SSLContext} used to create new sockets
 */
public TLSProtocolSocketFactory(X509KeyManager keyMgr, X509TrustManager trustMgr, HostnameVerifier verifier) 
        throws IllegalArgumentException {
    
    keyManagers = new X509KeyManager[] { keyMgr };
            
    // Note: There is a huge difference with SSLContext.init between:
    //    1) passing a null for TrustManager[]
    //    2) passing a TrustManager[] that contains 1 null member.
    //
    // The former causes the default trust manager set to be used. That's what we want 
    // if we TLS peer authN to happen (in the default way).
    // The latter effectively disables trust processing entirely (but not in the way we'd probably want).
    // So we need to make sure we don't do the latter.
    if (trustMgr != null) {
        trustManagers = new X509TrustManager[] { trustMgr };
    } else {
        trustManagers = null;
    }
    
    hostnameVerifier = verifier;
    
    secureRandom = null;
    
    init();
}
 
Example 6
Project: apache-tomcat-7.0.73-with-comment   File: NioEndpoint.java   Source Code and License 6 votes vote down vote up
public KeyManager[] wrap(KeyManager[] managers) {
    if (managers==null) return null;
    KeyManager[] result = new KeyManager[managers.length];
    for (int i=0; i<result.length; i++) {
        if (managers[i] instanceof X509KeyManager && getKeyAlias()!=null) {
            String keyAlias = getKeyAlias();
            // JKS keystores always convert the alias name to lower case
            if ("jks".equalsIgnoreCase(getKeystoreType())) {
                keyAlias = keyAlias.toLowerCase(Locale.ENGLISH);
            }
            result[i] = new NioX509KeyManager((X509KeyManager) managers[i], keyAlias);
        } else {
            result[i] = managers[i];
        }
    }
    return result;
}
 
Example 7
Project: lazycat   File: NioEndpoint.java   Source Code and License 6 votes vote down vote up
public KeyManager[] wrap(KeyManager[] managers) {
	if (managers == null)
		return null;
	KeyManager[] result = new KeyManager[managers.length];
	for (int i = 0; i < result.length; i++) {
		if (managers[i] instanceof X509KeyManager && getKeyAlias() != null) {
			String keyAlias = getKeyAlias();
			// JKS keystores always convert the alias name to lower case
			if ("jks".equalsIgnoreCase(getKeystoreType())) {
				keyAlias = keyAlias.toLowerCase(Locale.ENGLISH);
			}
			result[i] = new NioX509KeyManager((X509KeyManager) managers[i], keyAlias);
		} else {
			result[i] = managers[i];
		}
	}
	return result;
}
 
Example 8
Project: beyondj   File: SslContextFactory.java   Source Code and License 6 votes vote down vote up
protected KeyManager[] getKeyManagers(KeyStore keyStore) throws Exception {
      KeyManager[] managers = null;
      if (keyStore != null) {
          KeyManagerFactory keyManagerFactory =
KeyManagerFactory.getInstance(sslConfig.getKeyManagerFactoryAlgorithm());
          keyManagerFactory.init(keyStore, sslConfig.getKeyManagerPassword() == null?
		   (sslConfig.getKeyStorePassword() == null?null:
		    sslConfig.getKeyStorePassword().toCharArray()):
		   sslConfig.getKeyManagerPassword().toCharArray());
          managers = keyManagerFactory.getKeyManagers();

          if (sslConfig.getCertAlias() != null) {
              for (int idx = 0; idx < managers.length; idx++) {
                  if (managers[idx] instanceof X509KeyManager) {
                      managers[idx] = new AliasedX509ExtendedKeyManager(sslConfig.getCertAlias(),
							  (X509KeyManager)managers[idx]);
                  }
              }
          }
      }
      return managers;
  }
 
Example 9
Project: conscrypt   File: NativeSsl.java   Source Code and License 6 votes vote down vote up
void chooseClientCertificate(byte[] keyTypeBytes, byte[][] asn1DerEncodedPrincipals)
        throws SSLException, CertificateEncodingException {
    Set<String> keyTypesSet = SSLUtils.getSupportedClientKeyTypes(keyTypeBytes);
    String[] keyTypes = keyTypesSet.toArray(new String[keyTypesSet.size()]);

    X500Principal[] issuers;
    if (asn1DerEncodedPrincipals == null) {
        issuers = null;
    } else {
        issuers = new X500Principal[asn1DerEncodedPrincipals.length];
        for (int i = 0; i < asn1DerEncodedPrincipals.length; i++) {
            issuers[i] = new X500Principal(asn1DerEncodedPrincipals[i]);
        }
    }
    X509KeyManager keyManager = parameters.getX509KeyManager();
    String alias = (keyManager != null)
            ? aliasChooser.chooseClientAlias(keyManager, issuers, keyTypes)
            : null;
    setCertificate(alias);
}
 
Example 10
Project: conscrypt   File: SSLContextTest.java   Source Code and License 6 votes vote down vote up
@Test
public void test_SSLContext_x509AndPskConfiguration_defaultProviderOnly() throws Exception {
    // Test the scenario where an X509TrustManager and PSKKeyManager are provided.
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(new KeyManager[] {PSKKeyManagerProxy.getConscryptPSKKeyManager(
                            new PSKKeyManagerProxy())},
            null, // Use default trust managers, one of which is an X.509 one.
            null);
    List<String> expectedCipherSuites =
            new ArrayList<String>(StandardNames.CIPHER_SUITES_DEFAULT_PSK);
    expectedCipherSuites.addAll(StandardNames.CIPHER_SUITES_DEFAULT);
    assertEnabledCipherSuites(expectedCipherSuites, sslContext);

    // Test the scenario where an X509KeyManager and PSKKeyManager are provided.
    sslContext = SSLContext.getInstance("TLS");
    // Just an arbitrary X509KeyManager -- it won't be invoked in this test.
    X509KeyManager x509KeyManager = new RandomPrivateKeyX509ExtendedKeyManager(null);
    sslContext.init(
            new KeyManager[] {x509KeyManager,
                    PSKKeyManagerProxy.getConscryptPSKKeyManager(new PSKKeyManagerProxy())},
            new TrustManager[0], null);
    assertEnabledCipherSuites(expectedCipherSuites, sslContext);
}
 
Example 11
Project: conscrypt   File: X509KeyManagerTest.java   Source Code and License 6 votes vote down vote up
private void test_ChooseClientAlias_KeyType(String clientKeyType, String caKeyType,
        String selectedKeyType, boolean succeeds) throws Exception {
    TestKeyStore ca = new TestKeyStore.Builder().keyAlgorithms(caKeyType).build();
    TestKeyStore client = new TestKeyStore.Builder()
                                  .keyAlgorithms(clientKeyType)
                                  .signer(ca.getPrivateKey(caKeyType, caKeyType))
                                  .build();

    KeyManagerFactory kmf =
            KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(client.keyStore, client.keyPassword);

    String[] keyTypes = new String[] {selectedKeyType};
    KeyManager[] managers = kmf.getKeyManagers();
    for (KeyManager manager : managers) {
        if (manager instanceof X509KeyManager) {
            String alias = ((X509KeyManager) manager).chooseClientAlias(keyTypes, null, null);
            if (succeeds) {
                assertNotNull(alias);
            } else {
                assertNull(alias);
            }
        }
    }
}
 
Example 12
Project: PhoneChat   File: SslContextFactory.java   Source Code and License 6 votes vote down vote up
protected KeyManager[] getKeyManagers(KeyStore keyStore) throws Exception
{
    KeyManager[] managers = null;

    if (keyStore != null)
    {
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(_keyManagerFactoryAlgorithm);
        keyManagerFactory.init(keyStore,_keyManagerPassword == null?(_keyStorePassword == null?null:_keyStorePassword.toString().toCharArray()):_keyManagerPassword.toString().toCharArray());
        managers = keyManagerFactory.getKeyManagers();

        if (_certAlias != null)
        {
            for (int idx = 0; idx < managers.length; idx++)
            {
                if (managers[idx] instanceof X509KeyManager)
                {
                    managers[idx] = new AliasedX509ExtendedKeyManager(_certAlias,(X509KeyManager)managers[idx]);
                }
            }
        }
    }

    return managers;
}
 
Example 13
Project: fdroid   File: LocalRepoKeyStore.java   Source Code and License 6 votes vote down vote up
private void addToStore(String alias, KeyPair kp, Certificate cert) throws KeyStoreException,
        NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException {
    Certificate[] chain = {
        cert,
    };
    keyStore.setKeyEntry(alias, kp.getPrivate(),
            "".toCharArray(), chain);

    keyStore.store(new FileOutputStream(keyStoreFile), "".toCharArray());

    /*
     * After adding an entry to the keystore we need to create a fresh
     * KeyManager by reinitializing the KeyManagerFactory with the new key
     * store content and then rewrapping the default KeyManager with our own
     */
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());

    keyManagerFactory.init(keyStore, "".toCharArray());
    KeyManager defaultKeyManager = keyManagerFactory.getKeyManagers()[0];
    KeyManager wrappedKeyManager = new KerplappKeyManager((X509KeyManager) defaultKeyManager);
    keyManagers = new KeyManager[] {
        wrappedKeyManager,
    };
}
 
Example 14
Project: AppHub   File: LocalRepoKeyStore.java   Source Code and License 6 votes vote down vote up
private void addToStore(String alias, KeyPair kp, Certificate cert) throws KeyStoreException,
        NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException {
    Certificate[] chain = {
        cert,
    };
    keyStore.setKeyEntry(alias, kp.getPrivate(),
            "".toCharArray(), chain);

    keyStore.store(new FileOutputStream(keyStoreFile), "".toCharArray());

    /*
     * After adding an entry to the keystore we need to create a fresh
     * KeyManager by reinitializing the KeyManagerFactory with the new key
     * store content and then rewrapping the default KeyManager with our own
     */
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());

    keyManagerFactory.init(keyStore, "".toCharArray());
    KeyManager defaultKeyManager = keyManagerFactory.getKeyManagers()[0];
    KeyManager wrappedKeyManager = new KerplappKeyManager((X509KeyManager) defaultKeyManager);
    keyManagers = new KeyManager[] {
        wrappedKeyManager,
    };
}
 
Example 15
Project: nexus-public   File: ReloadableX509KeyManager.java   Source Code and License 6 votes vote down vote up
/**
 * Finds and replaces the X509KeyManager with a ReloadableX509KeyManager.  If there is more then one, only the first
 * one will be replaced.
 *
 * @param reloadableX509KeyManager an existing ReloadableX509KeyManager, or null if one does not exist.
 * @param keyManagers              an array of KeyManagers that is expected to contain a X509KeyManager.
 * @return a newly create ReloadableX509KeyManager
 * @throws NoSuchAlgorithmException
 *                               thrown if a X509KeyManager cannot be found in the array.
 * @throws IllegalStateException thrown if a ReloadableX509KeyManager is found in the array.
 */
public static ReloadableX509KeyManager replaceX509KeyManager(ReloadableX509KeyManager reloadableX509KeyManager,
                                                             final KeyManager[] keyManagers)
    throws NoSuchAlgorithmException
{
  for (int ii = 0; ii < keyManagers.length; ii++) {
    if (ReloadableX509KeyManager.class.isInstance(keyManagers[ii])) {
      throw new IllegalStateException(
          "A ReloadableX509KeyManager has already been set for this KeyManager[]");
    }

    if (X509KeyManager.class.isInstance(keyManagers[ii])) {
      if (reloadableX509KeyManager == null) {
        reloadableX509KeyManager = new ReloadableX509KeyManager((X509KeyManager) keyManagers[ii]);
      }
      else {
        reloadableX509KeyManager.setDelegateKeyManager((X509KeyManager) keyManagers[ii]);
      }

      keyManagers[ii] = reloadableX509KeyManager;
      return reloadableX509KeyManager;
    }
  }

  throw new NoSuchAlgorithmException("No X509KeyManager found in KeyManager[]");
}
 
Example 16
Project: nexus-public   File: KeyStoreManagerImplTest.java   Source Code and License 6 votes vote down vote up
/**
 * Verifies a KeyPair is generated and added to the keyManager.
 */
@Test
public void testKeyPairGeneration() throws Exception {
  // create the key pair
  keyStoreManager.generateAndStoreKeyPair("Joe Coder", "dev", "codeSoft", "AnyTown", "state", "US");

  // verify the KeyManager[] only contains one key
  KeyManager[] keyManagers = keyStoreManager.getKeyManagers();
  assertThat(keyManagers, notNullValue());
  assertThat(keyManagers, arrayWithSize(1));
  assertThat(keyManagers[0], instanceOf(X509KeyManager.class));
  assertThat(
      ((X509KeyManager) keyManagers[0]).getCertificateChain(PRIVATE_KEY_ALIAS)[0].getSubjectDN().getName(),
      equalTo("CN=Joe Coder,OU=dev,O=codeSoft,L=AnyTown,ST=state,C=US"));

  // verify the TrustManager[] does not have any certs, we have not trusted anyone yet.
  TrustManager[] trustManagers = keyStoreManager.getTrustManagers();
  assertThat(trustManagers, notNullValue());
  assertThat(trustManagers, arrayWithSize(1));
  assertThat(trustManagers[0], instanceOf(X509TrustManager.class));
  assertThat(((X509TrustManager) trustManagers[0]).getAcceptedIssuers(), emptyArray());
}
 
Example 17
Project: nexus-public   File: KeyStoreManagerImplTest.java   Source Code and License 6 votes vote down vote up
/**
 * Tests recreating the key pair will update the KeyManager.
 */
@Test
public void testReKeyPairGeneration() throws Exception {
  // create the key pair
  keyStoreManager.generateAndStoreKeyPair("Original Key", "dev", "codeSoft", "AnyTown", "state", "US");

  KeyManager[] originalKeyManagers = keyStoreManager.getKeyManagers();

  keyStoreManager.generateAndStoreKeyPair("New Key", "dev", "codeSoft", "AnyTown", "state", "US");

  String expectedDN = "CN=New Key,OU=dev,O=codeSoft,L=AnyTown,ST=state,C=US";

  assertThat(originalKeyManagers, notNullValue());
  assertThat(originalKeyManagers, arrayWithSize(1));
  assertThat(originalKeyManagers[0], instanceOf(X509KeyManager.class));
  assertThat(((X509KeyManager) originalKeyManagers[0]).getCertificateChain(
      PRIVATE_KEY_ALIAS)[0].getSubjectDN().getName(), equalTo(expectedDN));

  KeyManager[] newKeyManagers = keyStoreManager.getKeyManagers();
  assertThat(newKeyManagers, notNullValue());
  assertThat(newKeyManagers, arrayWithSize(1));
  assertThat(newKeyManagers[0], instanceOf(X509KeyManager.class));
  assertThat(
      ((X509KeyManager) newKeyManagers[0]).getCertificateChain(PRIVATE_KEY_ALIAS)[0].getSubjectDN().getName(),
      equalTo(expectedDN));
}
 
Example 18
Project: ipf-oht-atna   File: SecurityDomain.java   Source Code and License 6 votes vote down vote up
/**
 * If a keystore alias is defined, then override the key manager assigned
 * to with an alias-sensitive wrapper that selects the proper key from your
 * assigned key alias.
 */
private void fixKeyManagers() {
    // If the key manager factory is null, do not continue
    if (null == keyManagerFactory || null == keyManagerFactory.getKeyManagers()) {
        return;
    }
    KeyManager[] defaultKeyManagers = keyManagerFactory.getKeyManagers();
    KeyManager[] newKeyManagers = new KeyManager[defaultKeyManagers.length];

    KeyManager mgr = null;
    for (int i = 0; i < defaultKeyManagers.length; i++) {
        mgr = defaultKeyManagers[i];
        // If we're looking at an X509 Key manager, then wrap it in our
        // alias-selective manager
        if (mgr instanceof X509KeyManager) {
            mgr = new AliasSensitiveX509KeyManager(this, (X509KeyManager) mgr);
        }
        newKeyManagers[i] = mgr;
    }

    keyManagers = newKeyManagers;
}
 
Example 19
Project: Tank   File: AutoGeneratingContextSelector.java   Source Code and License 6 votes vote down vote up
public synchronized SSLContext select(InetSocketAddress target) {
    String host = target.getHostName();
    SSLContext sslContext = contextCache.get(host);
    if (sslContext == null) {
        try {
            X509KeyManager km = createKeyMaterial(host);
            sslContext = SSLContext.getInstance("SSLv3");
            sslContext.init(new KeyManager[] { km }, null, null);
            contextCache.put(host, sslContext);
        } catch (GeneralSecurityException gse) {
            logger.warning("Error obtaining the SSLContext: "
                    + gse.getLocalizedMessage());
        }
    }
    return sslContext;
}
 
Example 20
Project: Tank   File: AutoGeneratingContextSelector.java   Source Code and License 6 votes vote down vote up
private X509KeyManager createKeyMaterial(String host)
        throws GeneralSecurityException {
    KeyPair keyPair;

    if (reuseKeys) {
        keyPair = new KeyPair(caCerts[0].getPublicKey(), caKey);
    } else {
        KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");
        keygen.initialize(2048, new SecureRandom());
        keyPair = keygen.generateKeyPair();
    }

    X500Principal subject = getSubjectPrincipal(host);
    Date begin = new Date();
    Date ends = new Date(begin.getTime() + DEFAULT_VALIDITY);

    X509Certificate cert = BouncyCastleCertificateUtils.sign(subject, keyPair
            .getPublic(), caCerts[0].getSubjectX500Principal(), caCerts[0]
            .getPublicKey(), caKey, begin, ends, getNextSerialNo());

    X509Certificate[] chain = new X509Certificate[caCerts.length + 1];
    System.arraycopy(caCerts, 0, chain, 1, caCerts.length);
    chain[0] = cert;

    return new SingleX509KeyManager(host, keyPair.getPrivate(), chain);
}
 
Example 21
Project: Tank   File: KeystoreUtils.java   Source Code and License 6 votes vote down vote up
public static X509KeyManager getKeyManagerForAlias(KeyStore keyStore,
        String alias, char[] password) throws GeneralSecurityException {
    Key key = keyStore.getKey(alias, password);
    Certificate[] chain = keyStore.getCertificateChain(alias);
    if (key instanceof PrivateKey) {
        X509Certificate[] certChain = new X509Certificate[chain.length];
        for (int i = 0; i < chain.length; i++) {
            if (chain[i] instanceof X509Certificate) {
                certChain[i] = (X509Certificate) chain[i];
            } else {
                throw new InvalidKeyException("CA cert[" + i
                        + "] is not an X509Certificate: " + chain[i]);
            }
        }
        return new SingleX509KeyManager(alias, (PrivateKey) key, certChain);
    } else {
        throw new InvalidKeyException(
                "The CA private key should implement PrivateKey");
    }
}
 
Example 22
Project: dss   File: DefaultKeyManager.java   Source Code and License 6 votes vote down vote up
/**
 * Loads the keystore.
 * 
 * @param keystore
 *            the keystore to load
 * @param ksPasswd
 *            keystore's password
 * @throws GeneralSecurityException
 *             Certificate/Keystore/Algorithm/... exception
 */
private void initKeyManager(KeyStore keystore, String ksPasswd) throws GeneralSecurityException {
	// initialize a new KMF with the ts we just loaded
	KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
	kmf.init(keystore, ksPasswd.toCharArray());

	// acquire X509 key manager from factory
	KeyManager[] kms = kmf.getKeyManagers();

	for (final KeyManager km : kms) {
		if (km instanceof X509KeyManager) {
			keyManager = (X509KeyManager) km;
			return;
		}
	}
	throw new NoSuchAlgorithmException("No X509KeyManager in KeyManagerFactory");
}
 
Example 23
Project: IoTgo_Android_App   File: SslContextFactory.java   Source Code and License 6 votes vote down vote up
protected KeyManager[] getKeyManagers(KeyStore keyStore) throws Exception
{
    KeyManager[] managers = null;

    if (keyStore != null)
    {
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(_keyManagerFactoryAlgorithm);
        keyManagerFactory.init(keyStore,_keyManagerPassword == null?(_keyStorePassword == null?null:_keyStorePassword.toString().toCharArray()):_keyManagerPassword.toString().toCharArray());
        managers = keyManagerFactory.getKeyManagers();

        if (_certAlias != null)
        {
            for (int idx = 0; idx < managers.length; idx++)
            {
                if (managers[idx] instanceof X509KeyManager)
                {
                    managers[idx] = new AliasedX509ExtendedKeyManager(_certAlias,(X509KeyManager)managers[idx]);
                }
            }
        }
    }

    return managers;
}
 
Example 24
Project: IoTgo_Android_App   File: SslContextFactory.java   Source Code and License 6 votes vote down vote up
protected KeyManager[] getKeyManagers(KeyStore keyStore) throws Exception
{
    KeyManager[] managers = null;

    if (keyStore != null)
    {
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(_keyManagerFactoryAlgorithm);
        keyManagerFactory.init(keyStore,_keyManagerPassword == null?(_keyStorePassword == null?null:_keyStorePassword.toString().toCharArray()):_keyManagerPassword.toString().toCharArray());
        managers = keyManagerFactory.getKeyManagers();

        if (_certAlias != null)
        {
            for (int idx = 0; idx < managers.length; idx++)
            {
                if (managers[idx] instanceof X509KeyManager)
                {
                    managers[idx] = new AliasedX509ExtendedKeyManager(_certAlias,(X509KeyManager)managers[idx]);
                }
            }
        }
    }

    return managers;
}
 
Example 25
Project: superfly   File: AuthSSLProtocolSocketFactory.java   Source Code and License 6 votes vote down vote up
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");
    }
    LOG.debug("Initializing key manager");
    KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(
        KeyManagerFactory.getDefaultAlgorithm());
    kmfactory.init(keystore, password != null ? password.toCharArray(): null);
    KeyManager[] keymanagers = kmfactory.getKeyManagers();
    for (int i = 0; i < keymanagers.length; i++) {
        if (keymanagers[i] instanceof X509KeyManager) {
            keymanagers[i] = new AuthSSLX509KeyManager((X509KeyManager) keymanagers[i]);
        }
    }
    return keymanagers; 
}
 
Example 26
Project: f-droid   File: LocalRepoKeyStore.java   Source Code and License 6 votes vote down vote up
private void addToStore(String alias, KeyPair kp, Certificate cert) throws KeyStoreException,
        NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException,
        UnrecoverableKeyException {
    Certificate[] chain = new Certificate[] {
            cert
    };
    keyStore.setKeyEntry(alias, kp.getPrivate(),
            "".toCharArray(), chain);

    keyStore.store(new FileOutputStream(keyStoreFile), "".toCharArray());

    /*
     * After adding an entry to the keystore we need to create a fresh
     * KeyManager by reinitializing the KeyManagerFactory with the new key
     * store content and then rewrapping the default KeyManager with our own
     */
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());

    keyManagerFactory.init(keyStore, "".toCharArray());
    KeyManager defaultKeyManager = keyManagerFactory.getKeyManagers()[0];
    KeyManager wrappedKeyManager = new KerplappKeyManager((X509KeyManager) defaultKeyManager);
    keyManagers = new KeyManager[] {
            wrappedKeyManager
    };
}
 
Example 27
Project: In-the-Box-Fork   File: KeyManagerFactoryTest.java   Source Code and License 6 votes vote down vote up
private void test_X509KeyManager_alias(X509KeyManager km, String alias, String keyType) {
    if (alias == null) {
        assertNull(km.getCertificateChain(alias));
        assertNull(km.getPrivateKey(alias));
        return;
    }

    X509Certificate[] certificateChain = km.getCertificateChain(alias);
    PrivateKey privateKey = km.getPrivateKey(alias);

    if (keyType == null) {
        keyType = privateKey.getAlgorithm();
    } else {
        assertEquals(keyType, certificateChain[0].getPublicKey().getAlgorithm());
        assertEquals(keyType, privateKey.getAlgorithm());
    }

    PrivateKeyEntry privateKeyEntry
            = TestKeyStore.privateKey(TEST_KEY_STORE.keyStore,
                                      TEST_KEY_STORE.storePassword,
                                      keyType);
    assertEquals(Arrays.asList(privateKeyEntry.getCertificateChain()),
                 Arrays.asList(certificateChain));
    assertEquals(privateKeyEntry.getPrivateKey(), privateKey);
}
 
Example 28
Project: PADListener   File: SSLSocketFactoryFactory.java   Source Code and License 6 votes vote down vote up
private X509KeyManager loadKeyMaterial(SiteData hostData) throws GeneralSecurityException, IOException {
    X509Certificate[] certs = null;
    String certEntry = hostData.tcpAddress != null ? hostData.tcpAddress + "_" + hostData.destPort : hostData.name;
    Certificate[] chain = keystoreCert.getCertificateChain(certEntry);
    if (chain != null) {
        certs = cast(chain);
    } else {
        throw new GeneralSecurityException(
                "Internal error: certificate chain for " + hostData.name
                        + " not found!");
    }

    PrivateKey pk = (PrivateKey) keystoreCert.getKey(certEntry, passwordCerts);
    if (pk == null) {
        throw new GeneralSecurityException(
                "Internal error: private key for " + hostData.name + " not found!");
    }
    _logger.finest("loading keys for " + certEntry);
    return new HostKeyManager(hostData, pk, certs);
}
 
Example 29
Project: PADListener   File: SSLKeyManager.java   Source Code and License 6 votes vote down vote up
public synchronized String[] getClientAliases(String keyType, Principal[] issuers) {
    if (_preferredKeyManager != null)
        return _preferredKeyManager.getClientAliases(keyType, issuers);
    
    List<String> allAliases = new ArrayList<String>();
    Iterator<String> it = _managers.keySet().iterator();
    while (it.hasNext()) {
        String source = it.next();
        X509KeyManager km = _managers.get(source);
        String[] aliases = km.getClientAliases(keyType, issuers);
        if (aliases != null) {
            for (int i=0; i<aliases.length; i++) {
                allAliases.add(source + SEP + aliases[i]);
            }
        }
    }
    return allAliases.toArray(new String[0]);
}
 
Example 30
Project: PADListener   File: SSLKeyManager.java   Source Code and License 6 votes vote down vote up
public synchronized String[] getServerAliases(String keyType, Principal[] issuers) {
    if (_preferredKeyManager != null)
        return _preferredKeyManager.getServerAliases(keyType, issuers);
    
    List<String> allAliases = new ArrayList<String>();
    Iterator<String> it = _managers.keySet().iterator();
    while (it.hasNext()) {
        String source = it.next();
        X509KeyManager km = _managers.get(source);
        String[] aliases = km.getServerAliases(keyType, issuers);
        if (aliases != null) {
            for (int i=0; i<aliases.length; i++) {
                allAliases.add(source + SEP + aliases[i]);
            }
        }
    }
    return allAliases.toArray(new String[0]);
}
 
Example 31
Project: jetty-websocket-android   File: SslContextFactory.java   Source Code and License 6 votes vote down vote up
protected KeyManager[] getKeyManagers(KeyStore keyStore) throws Exception
{
    KeyManager[] managers = null;

    if (keyStore != null)
    {
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(_keyManagerFactoryAlgorithm);
        keyManagerFactory.init(keyStore,_keyManagerPassword == null?(_keyStorePassword == null?null:_keyStorePassword.toString().toCharArray()):_keyManagerPassword.toString().toCharArray());
        managers = keyManagerFactory.getKeyManagers();

        if (_certAlias != null)
        {
            for (int idx = 0; idx < managers.length; idx++)
            {
                if (managers[idx] instanceof X509KeyManager)
                {
                    managers[idx] = new AliasedX509ExtendedKeyManager(_certAlias,(X509KeyManager)managers[idx]);
                }
            }
        }
    }

    return managers;
}
 
Example 32
Project: fdroidclient   File: LocalRepoKeyStore.java   Source Code and License 6 votes vote down vote up
private void addToStore(String alias, KeyPair kp, Certificate cert) throws KeyStoreException,
        NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException {
    Certificate[] chain = {
        cert,
    };
    keyStore.setKeyEntry(alias, kp.getPrivate(),
            "".toCharArray(), chain);

    keyStore.store(new FileOutputStream(keyStoreFile), "".toCharArray());

    /*
     * After adding an entry to the keystore we need to create a fresh
     * KeyManager by reinitializing the KeyManagerFactory with the new key
     * store content and then rewrapping the default KeyManager with our own
     */
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());

    keyManagerFactory.init(keyStore, "".toCharArray());
    KeyManager defaultKeyManager = keyManagerFactory.getKeyManagers()[0];
    KeyManager wrappedKeyManager = new KerplappKeyManager((X509KeyManager) defaultKeyManager);
    keyManagers = new KeyManager[] {
        wrappedKeyManager,
    };
}
 
Example 33
Project: WebSocket-for-Android   File: SslContextFactory.java   Source Code and License 6 votes vote down vote up
protected KeyManager[] getKeyManagers(KeyStore keyStore) throws Exception
{
    KeyManager[] managers = null;

    if (keyStore != null)
    {
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(_keyManagerFactoryAlgorithm);
        keyManagerFactory.init(keyStore,_keyManagerPassword == null?(_keyStorePassword == null?null:_keyStorePassword.toString().toCharArray()):_keyManagerPassword.toString().toCharArray());
        managers = keyManagerFactory.getKeyManagers();

        if (_certAlias != null)
        {
            for (int idx = 0; idx < managers.length; idx++)
            {
                if (managers[idx] instanceof X509KeyManager)
                {
                    managers[idx] = new AliasedX509ExtendedKeyManager(_certAlias,(X509KeyManager)managers[idx]);
                }
            }
        }
    }

    return managers;
}
 
Example 34
Project: vbrowser   File: SSLContextManager.java   Source Code and License 6 votes vote down vote up
/** 
 * Create a key manager which manages one single key.  
 */ 
private KeyManager createSingleKeyManager(KeyStore keyStore,String alias,Secret privKeyPasswd) throws Exception
{
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");

    keyManagerFactory.init(keyStore, privKeyPasswd.getChars());
    X509KeyManager managerImpl = (X509KeyManager)keyManagerFactory.getKeyManagers()[0];
    X509Certificate[] chain = managerImpl.getCertificateChain(alias); 

    // === //
    
    PrivateKey privKey ;
    privKey=(PrivateKey)keyStore.getKey(alias,privKeyPasswd.getChars());
    
    PrivateX509KeyManager manager=new PrivateX509KeyManager(chain,privKey); 
   
    for (X509Certificate cert:chain)
    {
        logger.debugPrintf("--- my cert chain ---\n"); 
        logger.debugPrintf(" - subject %s\n",cert.getSubjectDN()); 
    }

    return manager;
}
 
Example 35
Project: cloudhopper-commons   File: SslContextFactory.java   Source Code and License 6 votes vote down vote up
protected KeyManager[] getKeyManagers(KeyStore keyStore) throws Exception {
      KeyManager[] managers = null;
      if (keyStore != null) {
          KeyManagerFactory keyManagerFactory =
KeyManagerFactory.getInstance(sslConfig.getKeyManagerFactoryAlgorithm());
          keyManagerFactory.init(keyStore, sslConfig.getKeyManagerPassword() == null?
		   (sslConfig.getKeyStorePassword() == null?null:
		    sslConfig.getKeyStorePassword().toCharArray()):
		   sslConfig.getKeyManagerPassword().toCharArray());
          managers = keyManagerFactory.getKeyManagers();

          if (sslConfig.getCertAlias() != null) {
              for (int idx = 0; idx < managers.length; idx++) {
                  if (managers[idx] instanceof X509KeyManager) {
                      managers[idx] = new AliasedX509ExtendedKeyManager(sslConfig.getCertAlias(),
							  (X509KeyManager)managers[idx]);
                  }
              }
          }
      }
      return managers;
  }
 
Example 36
Project: elexis-3-core   File: CompositeX509KeyManager.java   Source Code and License 6 votes vote down vote up
public void addKeyStore(KeyStore keyStore, String keystorePass){
	synchronized (keyManagers) {
		try {
			KeyManagerFactory factory =
				KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
			factory.init(keyStore, keystorePass.toCharArray());
			KeyManager[] managers = factory.getKeyManagers();
			List<X509KeyManager> typedManagers = new ArrayList<>();
			for (KeyManager keyManager : managers) {
				if (keyManager instanceof X509KeyManager) {
					typedManagers.add((X509KeyManager) keyManager);
				}
			}
			keyManagers.put(keyStore, typedManagers);
		} catch (NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException e) {
			LoggerFactory.getLogger(getClass()).error("Could not add trust store", e);
		}
	}
}
 
Example 37
Project: mina-ftpserver   File: DefaultSslConfiguration.java   Source Code and License 6 votes vote down vote up
private SSLContext initContext() throws GeneralSecurityException {
    KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();

    // wrap key managers to allow us to control their behavior
    // (FTPSERVER-93)
    for (int i = 0; i < keyManagers.length; i++) {
        if (ClassUtils.extendsClass(keyManagers[i].getClass(),
                "javax.net.ssl.X509ExtendedKeyManager")) {
            keyManagers[i] = new ExtendedAliasKeyManager(keyManagers[i],
                    keyAlias);
        } else if (keyManagers[i] instanceof X509KeyManager) {
            keyManagers[i] = new AliasKeyManager(keyManagers[i], keyAlias);
        }
    }

    // create and initialize the SSLContext
    SSLContext ctx = SSLContext.getInstance(sslProtocol);
    ctx.init(keyManagers, trustManagerFactory.getTrustManagers(), null);
    //Create the socket factory
    return ctx;
}
 
Example 38
Project: springboot-shiro-cas-mybatis   File: FileTrustStoreSslSocketFactory.java   Source Code and License 5 votes vote down vote up
/**
 * Gets the trusted ssl context.
 *
 * @param trustStoreFile the trust store file
 * @param trustStorePassword the trust store password
 * @param trustStoreType the trust store type
 * @return the trusted ssl context
 */
private static SSLContext getTrustedSslContext(final File trustStoreFile, final String trustStorePassword,
                                        final String trustStoreType) {
    try {

        if (!trustStoreFile.exists() || !trustStoreFile.canRead()) {
            throw new FileNotFoundException("Truststore file cannot be located at "
                + trustStoreFile.getCanonicalPath());
        }

        final KeyStore casTrustStore = KeyStore.getInstance(trustStoreType);
        final char[] trustStorePasswordCharArray = trustStorePassword.toCharArray();

        try (FileInputStream casStream = new FileInputStream(trustStoreFile)) {
            casTrustStore.load(casStream, trustStorePasswordCharArray);
        }

        final String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
        final X509KeyManager customKeyManager = getKeyManager("PKIX", casTrustStore, trustStorePasswordCharArray);
        final X509KeyManager jvmKeyManager = getKeyManager(defaultAlgorithm, null, null);
        final X509TrustManager customTrustManager = getTrustManager("PKIX", casTrustStore);
        final X509TrustManager jvmTrustManager = getTrustManager(defaultAlgorithm, null);

        final KeyManager[] keyManagers = {
                new CompositeX509KeyManager(Arrays.asList(jvmKeyManager, customKeyManager))
        };
        final TrustManager[] trustManagers = {
                new CompositeX509TrustManager(Arrays.asList(jvmTrustManager, customTrustManager))
        };

        final SSLContext context = SSLContexts.custom().useSSL().build();
        context.init(keyManagers, trustManagers, null);
        return context;

    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw new RuntimeException(e);
    }
}
 
Example 39
Project: springboot-shiro-cas-mybatis   File: FileTrustStoreSslSocketFactory.java   Source Code and License 5 votes vote down vote up
@Override
public String chooseClientAlias(final String[] keyType, final Principal[] issuers, final Socket socket) {
    for (final X509KeyManager keyManager : keyManagers) {
        final String alias = keyManager.chooseClientAlias(keyType, issuers, socket);
        if (alias != null) {
            return alias;
        }
    }
    return null;
}
 
Example 40
Project: springboot-shiro-cas-mybatis   File: FileTrustStoreSslSocketFactory.java   Source Code and License 5 votes vote down vote up
@Override
public String chooseServerAlias(final String keyType, final Principal[] issuers, final Socket socket) {
    for (final X509KeyManager keyManager : keyManagers) {
        final String alias = keyManager.chooseServerAlias(keyType, issuers, socket);
        if (alias != null) {
            return alias;
        }
    }
    return null;
}
 
Example 41
Project: springboot-shiro-cas-mybatis   File: FileTrustStoreSslSocketFactory.java   Source Code and License 5 votes vote down vote up
@Override
public PrivateKey getPrivateKey(final String alias) {
    for (final X509KeyManager keyManager : keyManagers) {
        final PrivateKey privateKey = keyManager.getPrivateKey(alias);
        if (privateKey != null) {
            return privateKey;
        }
    }
    return null;
}
 
Example 42
Project: springboot-shiro-cas-mybatis   File: FileTrustStoreSslSocketFactory.java   Source Code and License 5 votes vote down vote up
@Override
public X509Certificate[] getCertificateChain(final String alias) {
    for (final X509KeyManager keyManager : keyManagers) {
        final X509Certificate[] chain = keyManager.getCertificateChain(alias);
        if (chain != null && chain.length > 0) {
            return chain;
        }
    }
    return null;
}
 
Example 43
Project: springboot-shiro-cas-mybatis   File: FileTrustStoreSslSocketFactory.java   Source Code and License 5 votes vote down vote up
@Override
public String[] getClientAliases(final String keyType, final Principal[] issuers) {
    final List<String> aliases = new ArrayList<>();
    for (final X509KeyManager keyManager : keyManagers) {
        final List<String> list = Arrays.asList(keyManager.getClientAliases(keyType, issuers));
        aliases.addAll(list);
    }
    return aliases.toArray(new String[] {});
}
 
Example 44
Project: springboot-shiro-cas-mybatis   File: FileTrustStoreSslSocketFactory.java   Source Code and License 5 votes vote down vote up
@Override
public  String[] getServerAliases(final String keyType, final Principal[] issuers) {
    final List<String> aliases = new ArrayList<>();
    for (final X509KeyManager keyManager : keyManagers) {
        final List<String> list = Arrays.asList(keyManager.getServerAliases(keyType, issuers));
        aliases.addAll(list);
    }
    return aliases.toArray(new String[] {});
}
 
Example 45
Project: springboot-shiro-cas-mybatis   File: FileTrustStoreSslSocketFactory.java   Source Code and License 5 votes vote down vote up
/**
 * Gets the trusted ssl context.
 *
 * @param trustStoreFile the trust store file
 * @param trustStorePassword the trust store password
 * @param trustStoreType the trust store type
 * @return the trusted ssl context
 */
private static SSLContext getTrustedSslContext(final File trustStoreFile, final String trustStorePassword,
                                        final String trustStoreType) {
    try {

        if (!trustStoreFile.exists() || !trustStoreFile.canRead()) {
            throw new FileNotFoundException("Truststore file cannot be located at " + trustStoreFile.getCanonicalPath());
        }

        final KeyStore casTrustStore = KeyStore.getInstance(trustStoreType);
        final char[] trustStorePasswordCharArray = trustStorePassword.toCharArray();

        try (final FileInputStream casStream = new FileInputStream(trustStoreFile)) {
            casTrustStore.load(casStream, trustStorePasswordCharArray);
        }

        final String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
        final X509KeyManager customKeyManager = getKeyManager("PKIX", casTrustStore, trustStorePasswordCharArray);
        final X509KeyManager jvmKeyManager = getKeyManager(defaultAlgorithm, null, null);
        final X509TrustManager customTrustManager = getTrustManager("PKIX", casTrustStore);
        final X509TrustManager jvmTrustManager = getTrustManager(defaultAlgorithm, null);

        final KeyManager[] keyManagers = {
                new CompositeX509KeyManager(Arrays.asList(jvmKeyManager, customKeyManager))
        };
        final TrustManager[] trustManagers = {
                new CompositeX509TrustManager(Arrays.asList(jvmTrustManager, customTrustManager))
        };

        final SSLContext context = SSLContexts.custom().useSSL().build();
        context.init(keyManagers, trustManagers, null);
        return context;

    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw new RuntimeException(e);
    }
}
 
Example 46
Project: springboot-shiro-cas-mybatis   File: FileTrustStoreSslSocketFactory.java   Source Code and License 5 votes vote down vote up
@Override
public String chooseClientAlias(final String[] keyType, final Principal[] issuers, final Socket socket) {
    for (final X509KeyManager keyManager : keyManagers) {
        final String alias = keyManager.chooseClientAlias(keyType, issuers, socket);
        if (alias != null) {
            return alias;
        }
    }
    return null;
}
 
Example 47
Project: springboot-shiro-cas-mybatis   File: FileTrustStoreSslSocketFactory.java   Source Code and License 5 votes vote down vote up
@Override
public String chooseServerAlias(final String keyType, final Principal[] issuers, final Socket socket) {
    for (final X509KeyManager keyManager : keyManagers) {
        final String alias = keyManager.chooseServerAlias(keyType, issuers, socket);
        if (alias != null) {
            return alias;
        }
    }
    return null;
}
 
Example 48
Project: springboot-shiro-cas-mybatis   File: FileTrustStoreSslSocketFactory.java   Source Code and License 5 votes vote down vote up
@Override
public PrivateKey getPrivateKey(final String alias) {
    for (final X509KeyManager keyManager : keyManagers) {
        final PrivateKey privateKey = keyManager.getPrivateKey(alias);
        if (privateKey != null) {
            return privateKey;
        }
    }
    return null;
}
 
Example 49
Project: springboot-shiro-cas-mybatis   File: FileTrustStoreSslSocketFactory.java   Source Code and License 5 votes vote down vote up
@Override
public X509Certificate[] getCertificateChain(final String alias) {
    for (final X509KeyManager keyManager : keyManagers) {
        final X509Certificate[] chain = keyManager.getCertificateChain(alias);
        if (chain != null && chain.length > 0) {
            return chain;
        }
    }
    return null;
}
 
Example 50
Project: springboot-shiro-cas-mybatis   File: FileTrustStoreSslSocketFactory.java   Source Code and License 5 votes vote down vote up
@Override
public String[] getClientAliases(final String keyType, final Principal[] issuers) {
    final List<String> aliases = new ArrayList<>();
    for (final X509KeyManager keyManager : keyManagers) {
        final List<String> list = Arrays.asList(keyManager.getClientAliases(keyType, issuers));
        aliases.addAll(list);
    }
    return aliases.toArray(new String[] {});
}
 
Example 51
Project: springboot-shiro-cas-mybatis   File: FileTrustStoreSslSocketFactory.java   Source Code and License 5 votes vote down vote up
@Override
public  String[] getServerAliases(final String keyType, final Principal[] issuers) {
    final List<String> aliases = new ArrayList<>();
    for (final X509KeyManager keyManager : keyManagers) {
        final List<String> list = Arrays.asList(keyManager.getServerAliases(keyType, issuers));
        aliases.addAll(list);
    }
    return aliases.toArray(new String[] {});
}
 
Example 52
Project: cas-5.1.0   File: FileTrustStoreSslSocketFactory.java   Source Code and License 5 votes vote down vote up
/**
 * Gets the trusted ssl context.
 *
 * @param trustStoreFile     the trust store file
 * @param trustStorePassword the trust store password
 * @param trustStoreType     the trust store type
 * @return the trusted ssl context
 */
private static SSLContext getTrustedSslContext(final Resource trustStoreFile, final String trustStorePassword,
                                               final String trustStoreType) {
    try {

        final KeyStore casTrustStore = KeyStore.getInstance(trustStoreType);
        final char[] trustStorePasswordCharArray = trustStorePassword.toCharArray();

        try (InputStream casStream = trustStoreFile.getInputStream()) {
            casTrustStore.load(casStream, trustStorePasswordCharArray);
        }

        final String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
        final X509KeyManager customKeyManager = getKeyManager(ALG_NAME_PKIX, casTrustStore, trustStorePasswordCharArray);
        final X509KeyManager jvmKeyManager = getKeyManager(defaultAlgorithm, null, null);
        final X509TrustManager customTrustManager = getTrustManager(ALG_NAME_PKIX, casTrustStore);
        final X509TrustManager jvmTrustManager = getTrustManager(defaultAlgorithm, null);

        final KeyManager[] keyManagers = {
                new CompositeX509KeyManager(Arrays.asList(jvmKeyManager, customKeyManager))
        };
        final TrustManager[] trustManagers = {
                new CompositeX509TrustManager(Arrays.asList(jvmTrustManager, customTrustManager))
        };

        final SSLContext context = SSLContexts.custom().useProtocol("SSL").build();
        context.init(keyManagers, trustManagers, null);
        return context;

    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw Throwables.propagate(e);
    }
}
 
Example 53
Project: tomcat7   File: JSSESocketFactory.java   Source Code and License 5 votes vote down vote up
/**
 * Gets the initialized key managers.
 */
protected KeyManager[] getKeyManagers(String keystoreType,
                                      String keystoreProvider,
                                      String algorithm,
                                      String keyAlias)
            throws Exception {

    KeyManager[] kms = null;

    String keystorePass = getKeystorePassword();

    KeyStore ks = getKeystore(keystoreType, keystoreProvider, keystorePass);
    if (keyAlias != null && !ks.isKeyEntry(keyAlias)) {
        throw new IOException(
                sm.getString("jsse.alias_no_key_entry", keyAlias));
    }

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
    String keyPass = endpoint.getKeyPass();
    if (keyPass == null) {
        keyPass = keystorePass;
    }
    kmf.init(ks, keyPass.toCharArray());

    kms = kmf.getKeyManagers();
    if (keyAlias != null) {
        String alias = keyAlias;
        if (JSSESocketFactory.defaultKeystoreType.equals(keystoreType)) {
            alias = alias.toLowerCase(Locale.ENGLISH);
        }
        for(int i=0; i<kms.length; i++) {
            kms[i] = new JSSEKeyManager((X509KeyManager)kms[i], alias);
        }
    }

    return kms;
}
 
Example 54
Project: cas-server-4.2.1   File: FileTrustStoreSslSocketFactory.java   Source Code and License 5 votes vote down vote up
@Override
public String chooseClientAlias(final String[] keyType, final Principal[] issuers, final Socket socket) {
    for (final X509KeyManager keyManager : keyManagers) {
        final String alias = keyManager.chooseClientAlias(keyType, issuers, socket);
        if (alias != null) {
            return alias;
        }
    }
    return null;
}
 
Example 55
Project: cas-server-4.2.1   File: FileTrustStoreSslSocketFactory.java   Source Code and License 5 votes vote down vote up
@Override
public String chooseServerAlias(final String keyType, final Principal[] issuers, final Socket socket) {
    for (final X509KeyManager keyManager : keyManagers) {
        final String alias = keyManager.chooseServerAlias(keyType, issuers, socket);
        if (alias != null) {
            return alias;
        }
    }
    return null;
}
 
Example 56
Project: cas-server-4.2.1   File: FileTrustStoreSslSocketFactory.java   Source Code and License 5 votes vote down vote up
@Override
public PrivateKey getPrivateKey(final String alias) {
    for (final X509KeyManager keyManager : keyManagers) {
        final PrivateKey privateKey = keyManager.getPrivateKey(alias);
        if (privateKey != null) {
            return privateKey;
        }
    }
    return null;
}
 
Example 57
Project: cas-server-4.2.1   File: FileTrustStoreSslSocketFactory.java   Source Code and License 5 votes vote down vote up
@Override
public X509Certificate[] getCertificateChain(final String alias) {
    for (final X509KeyManager keyManager : keyManagers) {
        final X509Certificate[] chain = keyManager.getCertificateChain(alias);
        if (chain != null && chain.length > 0) {
            return chain;
        }
    }
    return null;
}
 
Example 58
Project: cas-server-4.2.1   File: FileTrustStoreSslSocketFactory.java   Source Code and License 5 votes vote down vote up
@Override
public String[] getClientAliases(final String keyType, final Principal[] issuers) {
    final List<String> aliases = new ArrayList<>();
    for (final X509KeyManager keyManager : keyManagers) {
        final List<String> list = Arrays.asList(keyManager.getClientAliases(keyType, issuers));
        aliases.addAll(list);
    }
    return aliases.toArray(new String[] {});
}
 
Example 59
Project: cas-server-4.2.1   File: FileTrustStoreSslSocketFactory.java   Source Code and License 5 votes vote down vote up
@Override
public  String[] getServerAliases(final String keyType, final Principal[] issuers) {
    final List<String> aliases = new ArrayList<>();
    for (final X509KeyManager keyManager : keyManagers) {
        final List<String> list = Arrays.asList(keyManager.getServerAliases(keyType, issuers));
        aliases.addAll(list);
    }
    return aliases.toArray(new String[] {});
}
 
Example 60
Project: lams   File: X509KeyManagerX509CredentialAdapter.java   Source Code and License 5 votes vote down vote up
/**
 * Constructor.
 * 
 * @param manager wrapped key manager
 * @param alias alias used to reference the credential in the key manager
 */
public X509KeyManagerX509CredentialAdapter(X509KeyManager manager, String alias) {
    if (manager == null) {
        throw new IllegalArgumentException("Key manager may not be null");
    }
    keyManager = manager;

    credentialAlias = DatatypeHelper.safeTrimOrNullString(alias);
    if (credentialAlias == null) {
        throw new IllegalArgumentException("Entity alias may not be null");
    }
}