Search in sources :

Example 1 with X509KeyManager

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

the class FileTrustStoreSslSocketFactory method getKeyManager.

/**
     * Gets key manager.
     *
     * @param algorithm the algorithm
     * @param keystore  the keystore
     * @param password  the password
     * @return the key manager
     * @throws Exception the exception
     */
private static X509KeyManager getKeyManager(final String algorithm, final KeyStore keystore, final char[] password) throws Exception {
    final KeyManagerFactory factory = KeyManagerFactory.getInstance(algorithm);
    factory.init(keystore, password);
    return (X509KeyManager) factory.getKeyManagers()[0];
}
Also used : X509KeyManager(javax.net.ssl.X509KeyManager) KeyManagerFactory(javax.net.ssl.KeyManagerFactory)

Example 2 with X509KeyManager

use of javax.net.ssl.X509KeyManager in project OpenAM by OpenRock.

the class AMX509KeyManagerImpl method initX509KeyManager.

// create sunX509KeyManager
//
// for example:
//     Create/load a keystore
//     Get instance of a "SunX509" KeyManagerFactory "kmf"
//     init the KeyManagerFactory with the keystore
public X509KeyManager initX509KeyManager(String ksType, String ksFile, String ksProvider, AMCallbackHandler cbHandle) {
    KeyManagerFactory kmf = null;
    // initialize KeyStore and get KeyManagerFactory 
    try {
        bundle = amCache.getResBundle(bundleName, Locale.getDefault());
        KeyStore.CallbackHandlerProtection callback = null;
        if (cbHandle != null) {
            callback = new KeyStore.CallbackHandlerProtection(cbHandle);
        } else {
            String passwdPrompt = bundle.getString("KeyStorePrompt");
            callback = new KeyStore.CallbackHandlerProtection(new AMCallbackHandler(passwdPrompt));
        }
        if (ksType.equalsIgnoreCase("JKS") || ksType.equalsIgnoreCase("PKCS12")) {
            builder = KeyStore.Builder.newInstance(ksType, Security.getProvider(ksProvider), new File(ksFile), callback);
        } else if (keyStoreType.equalsIgnoreCase("PKCS11")) {
            builder = KeyStore.Builder.newInstance(ksType, Security.getProvider(ksProvider), callback);
        }
        KeyStoreBuilderParameters param = new KeyStoreBuilderParameters(builder);
        kmf = KeyManagerFactory.getInstance(algorithm, provider);
        kmf.init(param);
    } catch (Exception e) {
        debug.error(e.toString());
    }
    return (X509KeyManager) kmf.getKeyManagers()[0];
}
Also used : KeyStoreBuilderParameters(javax.net.ssl.KeyStoreBuilderParameters) X509KeyManager(javax.net.ssl.X509KeyManager) KeyStore(java.security.KeyStore) File(java.io.File) KeyManagerFactory(javax.net.ssl.KeyManagerFactory)

Example 3 with X509KeyManager

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

the class X509KeyManagerTest method test_ChooseClientAlias_KeyType.

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);
            }
        }
    }
}
Also used : TestKeyStore(libcore.java.security.TestKeyStore) X509KeyManager(javax.net.ssl.X509KeyManager) X509KeyManager(javax.net.ssl.X509KeyManager) KeyManager(javax.net.ssl.KeyManager) KeyManagerFactory(javax.net.ssl.KeyManagerFactory)

Example 4 with X509KeyManager

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

the class ServerHandshakeImpl method processClientHello.

/**
     *
     * Processes Client Hello message.
     * Server responds to client hello message with server hello
     * and (if necessary) server certificate, server key exchange,
     * certificate request, and server hello done messages.
     */
void processClientHello() {
    CipherSuite cipher_suite;
    // check that clientHello contains CompressionMethod.null
    checkCompression: {
        for (int i = 0; i < clientHello.compression_methods.length; i++) {
            if (clientHello.compression_methods[i] == 0) {
                break checkCompression;
            }
        }
        fatalAlert(AlertProtocol.HANDSHAKE_FAILURE, "HANDSHAKE FAILURE. Incorrect client hello message");
    }
    byte[] server_version = clientHello.client_version;
    if (!ProtocolVersion.isSupported(clientHello.client_version)) {
        if (clientHello.client_version[0] >= 3) {
            // Protocol from the future, admit that the newest thing we know is TLSv1
            server_version = ProtocolVersion.TLSv1.version;
        } else {
            fatalAlert(AlertProtocol.PROTOCOL_VERSION, "PROTOCOL VERSION. Unsupported client version " + clientHello.client_version[0] + clientHello.client_version[1]);
        }
    }
    isResuming = false;
    FIND: if (clientHello.session_id.length != 0) {
        // client wishes to reuse session
        SSLSessionImpl sessionToResume;
        boolean reuseCurrent = false;
        // reuse current session
        if (session != null && Arrays.equals(session.id, clientHello.session_id)) {
            if (session.isValid()) {
                isResuming = true;
                break FIND;
            }
            reuseCurrent = true;
        }
        // find session in cash
        sessionToResume = findSessionToResume(clientHello.session_id);
        if (sessionToResume == null || !sessionToResume.isValid()) {
            if (!parameters.getEnableSessionCreation()) {
                if (reuseCurrent) {
                    // we can continue current session
                    sendWarningAlert(AlertProtocol.NO_RENEGOTIATION);
                    status = NOT_HANDSHAKING;
                    clearMessages();
                    return;
                }
                // throw AlertException
                fatalAlert(AlertProtocol.HANDSHAKE_FAILURE, "SSL Session may not be created");
            }
            session = null;
        } else {
            session = (SSLSessionImpl) sessionToResume.clone();
            isResuming = true;
        }
    }
    if (isResuming) {
        cipher_suite = session.cipherSuite;
        // clientHello.cipher_suites must include at least cipher_suite from the session
        checkCipherSuite: {
            for (int i = 0; i < clientHello.cipher_suites.length; i++) {
                if (cipher_suite.equals(clientHello.cipher_suites[i])) {
                    break checkCipherSuite;
                }
            }
            fatalAlert(AlertProtocol.HANDSHAKE_FAILURE, "HANDSHAKE FAILURE. Incorrect client hello message");
        }
    } else {
        cipher_suite = selectSuite(clientHello.cipher_suites);
        if (cipher_suite == null) {
            fatalAlert(AlertProtocol.HANDSHAKE_FAILURE, "HANDSHAKE FAILURE. NO COMMON SUITE");
        }
        if (!parameters.getEnableSessionCreation()) {
            fatalAlert(AlertProtocol.HANDSHAKE_FAILURE, "SSL Session may not be created");
        }
        session = new SSLSessionImpl(cipher_suite, parameters.getSecureRandom());
        if (engineOwner != null) {
            session.setPeer(engineOwner.getPeerHost(), engineOwner.getPeerPort());
        } else {
            session.setPeer(socketOwner.getInetAddress().getHostName(), socketOwner.getPort());
        }
    }
    recordProtocol.setVersion(server_version);
    session.protocol = ProtocolVersion.getByVersion(server_version);
    session.clientRandom = clientHello.random;
    // create server hello message
    serverHello = new ServerHello(parameters.getSecureRandom(), server_version, session.getId(), cipher_suite, //CompressionMethod.null
    (byte) 0);
    session.serverRandom = serverHello.random;
    send(serverHello);
    if (isResuming) {
        sendChangeCipherSpec();
        return;
    }
    //    create and send server certificate message if needed
    if (!cipher_suite.isAnonymous()) {
        // need to send server certificate
        X509Certificate[] certs = null;
        String certType = cipher_suite.getServerKeyType();
        if (certType == null) {
            fatalAlert(AlertProtocol.HANDSHAKE_FAILURE, "NO CERT TYPE FOR " + cipher_suite.getName());
        }
        // obtain certificates from key manager
        String alias = null;
        X509KeyManager km = parameters.getKeyManager();
        if (km instanceof X509ExtendedKeyManager) {
            X509ExtendedKeyManager ekm = (X509ExtendedKeyManager) km;
            if (this.socketOwner != null) {
                alias = ekm.chooseServerAlias(certType, null, this.socketOwner);
            } else {
                alias = ekm.chooseEngineServerAlias(certType, null, this.engineOwner);
            }
            if (alias != null) {
                certs = ekm.getCertificateChain(alias);
            }
        } else {
            alias = km.chooseServerAlias(certType, null, this.socketOwner);
            if (alias != null) {
                certs = km.getCertificateChain(alias);
            }
        }
        if (certs == null) {
            fatalAlert(AlertProtocol.HANDSHAKE_FAILURE, "NO SERVER CERTIFICATE FOUND");
            return;
        }
        session.localCertificates = certs;
        serverCert = new CertificateMessage(certs);
        privKey = km.getPrivateKey(alias);
        send(serverCert);
    }
    // create and send server key exchange message if needed
    RSAPublicKey rsakey = null;
    DHPublicKeySpec dhkeySpec = null;
    byte[] hash = null;
    BigInteger p = null;
    BigInteger g = null;
    KeyPairGenerator kpg = null;
    try {
        if (cipher_suite.keyExchange == CipherSuite.KEY_EXCHANGE_RSA_EXPORT) {
            PublicKey pk = serverCert.certs[0].getPublicKey();
            if (getRSAKeyLength(pk) > 512) {
                // key is longer than 512 bits
                kpg = KeyPairGenerator.getInstance("RSA");
                kpg.initialize(512);
            }
        } else if (cipher_suite.keyExchange == CipherSuite.KEY_EXCHANGE_DHE_DSS || cipher_suite.keyExchange == CipherSuite.KEY_EXCHANGE_DHE_DSS_EXPORT || cipher_suite.keyExchange == CipherSuite.KEY_EXCHANGE_DHE_RSA || cipher_suite.keyExchange == CipherSuite.KEY_EXCHANGE_DHE_RSA_EXPORT || cipher_suite.keyExchange == CipherSuite.KEY_EXCHANGE_DH_anon || cipher_suite.keyExchange == CipherSuite.KEY_EXCHANGE_DH_anon_EXPORT) {
            kpg = KeyPairGenerator.getInstance("DH");
            p = new BigInteger(1, DHParameters.getPrime());
            g = new BigInteger("2");
            DHParameterSpec spec = new DHParameterSpec(p, g);
            kpg.initialize(spec);
        }
    } catch (Exception e) {
        fatalAlert(AlertProtocol.INTERNAL_ERROR, "INTERNAL ERROR", e);
    }
    if (kpg != null) {
        // need to send server key exchange message
        DigitalSignature ds = new DigitalSignature(cipher_suite.authType);
        KeyPair kp = null;
        try {
            kp = kpg.genKeyPair();
            if (cipher_suite.keyExchange == CipherSuite.KEY_EXCHANGE_RSA_EXPORT) {
                rsakey = (RSAPublicKey) kp.getPublic();
            } else {
                DHPublicKey dhkey = (DHPublicKey) kp.getPublic();
                KeyFactory kf = KeyFactory.getInstance("DH");
                dhkeySpec = kf.getKeySpec(dhkey, DHPublicKeySpec.class);
            }
            if (!cipher_suite.isAnonymous()) {
                // calculate signed_params
                // init by private key which correspond to
                // server certificate
                ds.init(privKey);
                // use emphemeral key for key exchange
                privKey = kp.getPrivate();
                ds.update(clientHello.getRandom());
                ds.update(serverHello.getRandom());
                //FIXME 1_byte==0x00
                if (cipher_suite.keyExchange == CipherSuite.KEY_EXCHANGE_RSA_EXPORT) {
                    ServerKeyExchange.updateSignatureRsa(ds, rsakey.getModulus(), rsakey.getPublicExponent());
                } else {
                    ServerKeyExchange.updateSignatureDh(ds, dhkeySpec.getP(), dhkeySpec.getG(), dhkeySpec.getY());
                }
                hash = ds.sign();
            } else {
                // use emphemeral key for key exchange
                privKey = kp.getPrivate();
            }
        } catch (Exception e) {
            fatalAlert(AlertProtocol.INTERNAL_ERROR, "INTERNAL ERROR", e);
        }
        if (cipher_suite.keyExchange == CipherSuite.KEY_EXCHANGE_RSA_EXPORT) {
            serverKeyExchange = new ServerKeyExchange(rsakey.getModulus(), rsakey.getPublicExponent(), null, hash);
        } else {
            serverKeyExchange = new ServerKeyExchange(p, g, dhkeySpec.getY(), hash);
        }
        send(serverKeyExchange);
    }
    // CERTIFICATE_REQUEST
    certRequest: if (parameters.getWantClientAuth() || parameters.getNeedClientAuth()) {
        X509Certificate[] accepted;
        try {
            X509TrustManager tm = parameters.getTrustManager();
            accepted = tm.getAcceptedIssuers();
        } catch (ClassCastException e) {
            // don't send certificateRequest
            break certRequest;
        }
        byte[] requestedClientCertTypes = { CipherSuite.TLS_CT_RSA_SIGN, CipherSuite.TLS_CT_DSS_SIGN };
        certificateRequest = new CertificateRequest(requestedClientCertTypes, accepted);
        send(certificateRequest);
    }
    // SERVER_HELLO_DONE
    serverHelloDone = new ServerHelloDone();
    send(serverHelloDone);
    status = NEED_UNWRAP;
}
Also used : DHPublicKey(javax.crypto.interfaces.DHPublicKey) DHParameterSpec(javax.crypto.spec.DHParameterSpec) X509ExtendedKeyManager(javax.net.ssl.X509ExtendedKeyManager) RSAPublicKey(java.security.interfaces.RSAPublicKey) X509KeyManager(javax.net.ssl.X509KeyManager) KeyFactory(java.security.KeyFactory) KeyPair(java.security.KeyPair) PublicKey(java.security.PublicKey) RSAPublicKey(java.security.interfaces.RSAPublicKey) DHPublicKey(javax.crypto.interfaces.DHPublicKey) KeyPairGenerator(java.security.KeyPairGenerator) X509Certificate(java.security.cert.X509Certificate) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) X509TrustManager(javax.net.ssl.X509TrustManager) BigInteger(java.math.BigInteger) DHPublicKeySpec(javax.crypto.spec.DHPublicKeySpec)

Example 5 with X509KeyManager

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

the class SSLParametersImpl method createDefaultKeyManager.

private static X509KeyManager createDefaultKeyManager() throws KeyManagementException {
    try {
        String algorithm = KeyManagerFactory.getDefaultAlgorithm();
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
        kmf.init(null, null);
        KeyManager[] kms = kmf.getKeyManagers();
        return findX509KeyManager(kms);
    } catch (NoSuchAlgorithmException e) {
        throw new KeyManagementException(e);
    } catch (KeyStoreException e) {
        throw new KeyManagementException(e);
    } catch (UnrecoverableKeyException e) {
        throw new KeyManagementException(e);
    }
}
Also used : UnrecoverableKeyException(java.security.UnrecoverableKeyException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) X509KeyManager(javax.net.ssl.X509KeyManager) KeyManager(javax.net.ssl.KeyManager) KeyManagementException(java.security.KeyManagementException) KeyManagerFactory(javax.net.ssl.KeyManagerFactory)

Aggregations

X509KeyManager (javax.net.ssl.X509KeyManager)65 KeyManager (javax.net.ssl.KeyManager)31 KeyManagerFactory (javax.net.ssl.KeyManagerFactory)21 IOException (java.io.IOException)18 KeyStore (java.security.KeyStore)16 X509Certificate (java.security.cert.X509Certificate)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