Search in sources :

Example 31 with KeyPairGenerator

use of java.security.KeyPairGenerator in project robovm by robovm.

the class KeyPairGenerator4Test method test_initializeLjava_security_spec_AlgorithmParameterSpecLjava_security_SecureRandom.

/**
     * java.security.KeyPairGenerator#initialize(java.security.spec.AlgorithmParameterSpec,
     *        java.security.SecureRandom)
     */
public void test_initializeLjava_security_spec_AlgorithmParameterSpecLjava_security_SecureRandom() throws Exception {
    // create DSAParams
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DSA");
    keyPairGenerator.initialize(1024);
    DSAPublicKey key = (DSAPublicKey) keyPairGenerator.genKeyPair().getPublic();
    DSAParams params = key.getParams();
    KeyPairGenerator keyPair = KeyPairGenerator.getInstance("DSA");
    keyPair.initialize(new DSAParameterSpec(params.getP(), params.getQ(), params.getG()), new SecureRandom());
}
Also used : DSAParameterSpec(java.security.spec.DSAParameterSpec) SecureRandom(java.security.SecureRandom) KeyPairGenerator(java.security.KeyPairGenerator) DSAParams(java.security.interfaces.DSAParams) DSAPublicKey(java.security.interfaces.DSAPublicKey)

Example 32 with KeyPairGenerator

use of java.security.KeyPairGenerator in project robovm by robovm.

the class KeyFactory2Test method test_generatePrivateLjava_security_spec_KeySpec.

public void test_generatePrivateLjava_security_spec_KeySpec() throws Exception {
    // java.security.KeyFactory.generatePrivate(java.security.spec.KeySpec)
    for (int i = 0; i < keyfactAlgs.length; i++) {
        KeyFactory fact = KeyFactory.getInstance(keyfactAlgs[i], providerName);
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance(keyfactAlgs[i]);
        // We don't use
        SecureRandom random = new SecureRandom();
        // getInstance
        keyGen.initialize(StandardNames.getMinimumKeySize(keyfactAlgs[i]), random);
        KeepAlive keepalive = createKeepAlive(keyfactAlgs[i]);
        KeyPair keys = keyGen.generateKeyPair();
        if (keepalive != null) {
            keepalive.interrupt();
        }
        KeySpec privateKeySpec = fact.getKeySpec(keys.getPrivate(), StandardNames.getPrivateKeySpecClass(keyfactAlgs[i]));
        PrivateKey privateKey = fact.generatePrivate(privateKeySpec);
        assertEquals("generatePrivate generated different key for algorithm " + keyfactAlgs[i], Arrays.toString(keys.getPrivate().getEncoded()), Arrays.toString(privateKey.getEncoded()));
        privateKey = fact.generatePrivate(new PKCS8EncodedKeySpec(keys.getPrivate().getEncoded()));
        assertEquals("generatePrivate generated different key for algorithm " + keyfactAlgs[i], Arrays.toString(keys.getPrivate().getEncoded()), Arrays.toString(privateKey.getEncoded()));
    }
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) KeySpec(java.security.spec.KeySpec) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) SecureRandom(java.security.SecureRandom) KeyPairGenerator(java.security.KeyPairGenerator) KeyFactory(java.security.KeyFactory)

Example 33 with KeyPairGenerator

use of java.security.KeyPairGenerator 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 34 with KeyPairGenerator

use of java.security.KeyPairGenerator in project robovm by robovm.

the class KeyStorePrivateKeyEntryTest method testGetCertificateChain.

public void testGetCertificateChain() throws Exception {
    String certificateData = "-----BEGIN CERTIFICATE-----\n" + "MIICZTCCAdICBQL3AAC2MA0GCSqGSIb3DQEBAgUAMF8xCzAJBgNVBAYTAlVTMSAw\n" + "HgYDVQQKExdSU0EgRGF0YSBTZWN1cml0eSwgSW5jLjEuMCwGA1UECxMlU2VjdXJl\n" + "IFNlcnZlciBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw05NzAyMjAwMDAwMDBa\n" + "Fw05ODAyMjAyMzU5NTlaMIGWMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZv\n" + "cm5pYTESMBAGA1UEBxMJUGFsbyBBbHRvMR8wHQYDVQQKExZTdW4gTWljcm9zeXN0\n" + "ZW1zLCBJbmMuMSEwHwYDVQQLExhUZXN0IGFuZCBFdmFsdWF0aW9uIE9ubHkxGjAY\n" + "BgNVBAMTEWFyZ29uLmVuZy5zdW4uY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCB\n" + "iQKBgQCofmdY+PiUWN01FOzEewf+GaG+lFf132UpzATmYJkA4AEA/juW7jSi+LJk\n" + "wJKi5GO4RyZoyimAL/5yIWDV6l1KlvxyKslr0REhMBaD/3Z3EsLTTEf5gVrQS6sT\n" + "WMoSZAyzB39kFfsB6oUXNtV8+UKKxSxKbxvhQn267PeCz5VX2QIDAQABMA0GCSqG\n" + "SIb3DQEBAgUAA34AXl3at6luiV/7I9MN5CXYoPJYI8Bcdc1hBagJvTMcmlqL2uOZ\n" + "H9T5hNMEL9Tk6aI7yZPXcw/xI2K6pOR/FrMp0UwJmdxX7ljV6ZtUZf7pY492UqwC\n" + "1777XQ9UEZyrKJvF5ntleeO0ayBqLGVKCWzWZX9YsXCpv47FNLZbupE=\n" + "-----END CERTIFICATE-----\n";
    ByteArrayInputStream certArray;
    {
        try {
            certArray = new ByteArrayInputStream(certificateData.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e.getMessage());
        }
    }
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    Certificate certificate = cf.generateCertificate(certArray);
    assertTrue(certificate instanceof X509Certificate);
    String algorithm = certificate.getPublicKey().getAlgorithm();
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    PrivateKey privateKey = keyPair.getPrivate();
    // If all the certificate in the chain is X509Certificate,
    // KeyStore.PrivateKeyEntry will return a X509Certificate array.
    KeyStore.PrivateKeyEntry privateKeyEntry = new KeyStore.PrivateKeyEntry(privateKey, new Certificate[] { certificate });
    Certificate[] chain = privateKeyEntry.getCertificateChain();
    assertTrue(chain instanceof X509Certificate[]);
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) UnsupportedEncodingException(java.io.UnsupportedEncodingException) KeyPairGenerator(java.security.KeyPairGenerator) CertificateFactory(java.security.cert.CertificateFactory) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) ByteArrayInputStream(java.io.ByteArrayInputStream) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 35 with KeyPairGenerator

use of java.security.KeyPairGenerator in project robovm by robovm.

the class Signature2Test method getDsaKeys.

private static KeyPair getDsaKeys() throws Exception {
    if (DSA_KEYS == null) {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
        keyGen.initialize(1024);
        DSA_KEYS = keyGen.generateKeyPair();
    }
    return DSA_KEYS;
}
Also used : KeyPairGenerator(java.security.KeyPairGenerator)

Aggregations

KeyPairGenerator (java.security.KeyPairGenerator)197 KeyPair (java.security.KeyPair)145 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)43 SecureRandom (java.security.SecureRandom)39 PublicKey (java.security.PublicKey)27 PrivateKey (java.security.PrivateKey)26 X509Certificate (java.security.cert.X509Certificate)23 KeyFactory (java.security.KeyFactory)21 IOException (java.io.IOException)19 BigInteger (java.math.BigInteger)17 GeneralSecurityException (java.security.GeneralSecurityException)15 Signature (java.security.Signature)15 Date (java.util.Date)15 Cipher (javax.crypto.Cipher)15 KeyAgreement (javax.crypto.KeyAgreement)15 RSAPublicKey (java.security.interfaces.RSAPublicKey)14 X500Principal (javax.security.auth.x500.X500Principal)13 ECPrivateKey (java.security.interfaces.ECPrivateKey)12 ECPublicKey (java.security.interfaces.ECPublicKey)12 HashMap (java.util.HashMap)11