Search in sources :

Example 36 with X509KeyManager

use of javax.net.ssl.X509KeyManager in project iaf by ibissource.

the class SignaturePipeTest method testSign.

@Test
public void testSign() throws Exception {
    String pfxCertificate = "/Signature/certificate.pfx";
    String pfxPassword = "geheim";
    URL pfxURL = ClassUtils.getResourceURL(pfxCertificate);
    assertNotNull("PFX file not found", pfxURL);
    KeyStore keystore = PkiUtil.createKeyStore(pfxURL, pfxPassword, KeystoreType.PKCS12, "junittest");
    KeyManager[] keymanagers = PkiUtil.createKeyManagers(keystore, pfxPassword, null);
    if (keymanagers == null || keymanagers.length == 0) {
        fail("No keymanager found in PFX file [" + pfxCertificate + "]");
    }
    X509KeyManager keyManager = (X509KeyManager) keymanagers[0];
    PrivateKey privateKey = keyManager.getPrivateKey("1");
    String alias = "1";
    String[] aliases = null;
    if (privateKey == null) {
        try {
            aliases = keyManager.getServerAliases("RSA", null);
            if (aliases != null) {
                // Try the first alias
                privateKey = keyManager.getPrivateKey(aliases[0]);
                assertNotNull(privateKey);
                alias = aliases[0];
            }
        } catch (Exception e) {
            System.out.println("unable to retreive alias from PFX file");
        }
    }
    assertNotNull((aliases != null) ? ("found aliases " + Arrays.asList(aliases) + " in PFX file") : "no aliases found in PFX file", privateKey);
    pipe.setKeystore("/Signature/certificate.pfx");
    pipe.setKeystorePassword(pfxPassword);
    // GitHub Actions uses a different X509KeyManager, the first alias is 0 instead of 1;
    pipe.setKeystoreAlias(alias);
    configureAndStartPipe();
    PipeRunResult prr = doPipe(new Message(testMessage));
    // Base64 is meant to be able to handle data as String. Having it as bytes causes wrong handling, e.g. as parameters to XSLT
    assertFalse("base64 signature should not be binary", prr.getResult().isBinary());
    assertEquals(testSignature, prr.getResult().asString());
    assertEquals("success", prr.getPipeForward().getName());
}
Also used : PipeRunResult(nl.nn.adapterframework.core.PipeRunResult) PrivateKey(java.security.PrivateKey) Message(nl.nn.adapterframework.stream.Message) X509KeyManager(javax.net.ssl.X509KeyManager) KeyStore(java.security.KeyStore) X509KeyManager(javax.net.ssl.X509KeyManager) KeyManager(javax.net.ssl.KeyManager) URL(java.net.URL) PipeStartException(nl.nn.adapterframework.core.PipeStartException) Test(org.junit.Test)

Example 37 with X509KeyManager

use of javax.net.ssl.X509KeyManager in project cas by apereo.

the class FileTrustStoreSslSocketFactory method getTrustedSslContext.

/**
     * 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);
    }
}
Also used : InputStream(java.io.InputStream) SSLContext(javax.net.ssl.SSLContext) KeyStore(java.security.KeyStore) CertificateException(java.security.cert.CertificateException) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) X509KeyManager(javax.net.ssl.X509KeyManager) X509KeyManager(javax.net.ssl.X509KeyManager) KeyManager(javax.net.ssl.KeyManager)

Example 38 with X509KeyManager

use of javax.net.ssl.X509KeyManager in project tomcat by apache.

the class JSSEUtil method getKeyManagers.

@Override
public KeyManager[] getKeyManagers() throws Exception {
    String keystoreType = certificate.getCertificateKeystoreType();
    String keyAlias = certificate.getCertificateKeyAlias();
    String algorithm = sslHostConfig.getKeyManagerAlgorithm();
    String keyPass = certificate.getCertificateKeyPassword();
    // defaults vary between JSSE and OpenSSL.
    if (keyPass == null) {
        keyPass = certificate.getCertificateKeystorePassword();
    }
    KeyManager[] kms = null;
    KeyStore ks = certificate.getCertificateKeystore();
    if (ks == null) {
        // create an in-memory keystore and import the private key
        // and the certificate chain from the PEM files
        ks = KeyStore.getInstance("JKS");
        ks.load(null, null);
        PEMFile privateKeyFile = new PEMFile(SSLHostConfig.adjustRelativePath(certificate.getCertificateKeyFile() != null ? certificate.getCertificateKeyFile() : certificate.getCertificateFile()), keyPass);
        PEMFile certificateFile = new PEMFile(SSLHostConfig.adjustRelativePath(certificate.getCertificateFile()));
        Collection<Certificate> chain = new ArrayList<>();
        chain.addAll(certificateFile.getCertificates());
        if (certificate.getCertificateChainFile() != null) {
            PEMFile certificateChainFile = new PEMFile(SSLHostConfig.adjustRelativePath(certificate.getCertificateChainFile()));
            chain.addAll(certificateChainFile.getCertificates());
        }
        if (keyAlias == null) {
            keyAlias = "tomcat";
        }
        ks.setKeyEntry(keyAlias, privateKeyFile.getPrivateKey(), keyPass.toCharArray(), chain.toArray(new Certificate[chain.size()]));
    }
    if (keyAlias != null && !ks.isKeyEntry(keyAlias)) {
        throw new IOException(sm.getString("jsse.alias_no_key_entry", keyAlias));
    }
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
    kmf.init(ks, keyPass.toCharArray());
    kms = kmf.getKeyManagers();
    if (kms == null) {
        return kms;
    }
    if (keyAlias != null) {
        String alias = keyAlias;
        // JKS keystores always convert the alias name to lower case
        if ("JKS".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;
}
Also used : ArrayList(java.util.ArrayList) IOException(java.io.IOException) KeyStore(java.security.KeyStore) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) X509KeyManager(javax.net.ssl.X509KeyManager) X509KeyManager(javax.net.ssl.X509KeyManager) KeyManager(javax.net.ssl.KeyManager) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate) SSLHostConfigCertificate(org.apache.tomcat.util.net.SSLHostConfigCertificate)

Example 39 with X509KeyManager

use of javax.net.ssl.X509KeyManager in project camel by apache.

the class KeyManagersParametersTest method validateKeyManagers.

protected void validateKeyManagers(KeyManager[] kms) {
    assertEquals(1, kms.length);
    assertTrue(kms[0] instanceof X509KeyManager);
    X509KeyManager km = (X509KeyManager) kms[0];
    assertNotNull(km.getPrivateKey("server"));
}
Also used : X509KeyManager(javax.net.ssl.X509KeyManager)

Example 40 with X509KeyManager

use of javax.net.ssl.X509KeyManager in project robovm by robovm.

the class SSLSocketTest method test_SSLSocket_clientAuth_bogusAlias.

public void test_SSLSocket_clientAuth_bogusAlias() throws Exception {
    TestSSLContext c = TestSSLContext.create();
    SSLContext clientContext = SSLContext.getInstance("TLS");
    X509KeyManager keyManager = new X509KeyManager() {

        @Override
        public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) {
            return "bogus";
        }

        @Override
        public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) {
            throw new AssertionError();
        }

        @Override
        public X509Certificate[] getCertificateChain(String alias) {
            // return null for "bogus" alias
            return null;
        }

        @Override
        public String[] getClientAliases(String keyType, Principal[] issuers) {
            throw new AssertionError();
        }

        @Override
        public String[] getServerAliases(String keyType, Principal[] issuers) {
            throw new AssertionError();
        }

        @Override
        public PrivateKey getPrivateKey(String alias) {
            // return null for "bogus" alias
            return null;
        }
    };
    clientContext.init(new KeyManager[] { keyManager }, new TrustManager[] { c.clientTrustManager }, null);
    SSLSocket client = (SSLSocket) clientContext.getSocketFactory().createSocket(c.host, c.port);
    final SSLSocket server = (SSLSocket) c.serverSocket.accept();
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Future<Void> future = executor.submit(new Callable<Void>() {

        @Override
        public Void call() throws Exception {
            try {
                server.setNeedClientAuth(true);
                server.startHandshake();
                fail();
            } catch (SSLHandshakeException expected) {
            }
            return null;
        }
    });
    executor.shutdown();
    try {
        client.startHandshake();
        fail();
    } catch (SSLHandshakeException expected) {
    // before we would get a NullPointerException from passing
    // due to the null PrivateKey return by the X509KeyManager.
    }
    future.get();
    client.close();
    server.close();
    c.close();
}
Also used : SSLSocket(javax.net.ssl.SSLSocket) SSLContext(javax.net.ssl.SSLContext) X509Certificate(java.security.cert.X509Certificate) SocketException(java.net.SocketException) SocketTimeoutException(java.net.SocketTimeoutException) SSLProtocolException(javax.net.ssl.SSLProtocolException) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) SSLException(javax.net.ssl.SSLException) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) X509KeyManager(javax.net.ssl.X509KeyManager) ExecutorService(java.util.concurrent.ExecutorService) Socket(java.net.Socket) SSLSocket(javax.net.ssl.SSLSocket) ServerSocket(java.net.ServerSocket) SSLServerSocket(javax.net.ssl.SSLServerSocket)

Aggregations

X509KeyManager (javax.net.ssl.X509KeyManager)66 KeyManager (javax.net.ssl.KeyManager)32 KeyManagerFactory (javax.net.ssl.KeyManagerFactory)22 IOException (java.io.IOException)18 X509Certificate (java.security.cert.X509Certificate)17 KeyStore (java.security.KeyStore)16 SSLContext (javax.net.ssl.SSLContext)15 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)12 MethodSource (org.junit.jupiter.params.provider.MethodSource)12 GeneralSecurityException (java.security.GeneralSecurityException)8 CertificateException (java.security.cert.CertificateException)8 X509TrustManager (javax.net.ssl.X509TrustManager)8 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)7 PrivateKey (java.security.PrivateKey)7 TrustManager (javax.net.ssl.TrustManager)7 X509ExtendedKeyManager (javax.net.ssl.X509ExtendedKeyManager)7 UnifiedX509KeyManager (com.sun.enterprise.security.ssl.manager.UnifiedX509KeyManager)4 KeyFactory (java.security.KeyFactory)4 KeyPair (java.security.KeyPair)4 KeyPairGenerator (java.security.KeyPairGenerator)4