Search in sources :

Example 41 with PrivateKey

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

the class RandomPrivateKeyX509ExtendedKeyManager method getPrivateKey.

@Override
public PrivateKey getPrivateKey(String alias) {
    PrivateKey originalPrivateKey = super.getPrivateKey(alias);
    if (originalPrivateKey == null) {
        return null;
    }
    PrivateKey result;
    String keyAlgorithm = originalPrivateKey.getAlgorithm();
    try {
        KeyFactory keyFactory = KeyFactory.getInstance(keyAlgorithm);
        if ("RSA".equals(keyAlgorithm)) {
            RSAPrivateKeySpec originalKeySpec = keyFactory.getKeySpec(originalPrivateKey, RSAPrivateKeySpec.class);
            int keyLengthBits = originalKeySpec.getModulus().bitLength();
            // Use a cache because RSA key generation is slow.
            String cacheKey = keyAlgorithm + "-" + keyLengthBits;
            result = cachedKeys.get(cacheKey);
            if (result == null) {
                KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(keyAlgorithm);
                keyPairGenerator.initialize(keyLengthBits);
                result = keyPairGenerator.generateKeyPair().getPrivate();
                cachedKeys.put(cacheKey, result);
            }
        } else if ("DSA".equals(keyAlgorithm)) {
            DSAPrivateKeySpec originalKeySpec = keyFactory.getKeySpec(originalPrivateKey, DSAPrivateKeySpec.class);
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(keyAlgorithm);
            keyPairGenerator.initialize(new DSAParameterSpec(originalKeySpec.getP(), originalKeySpec.getQ(), originalKeySpec.getG()));
            result = keyPairGenerator.generateKeyPair().getPrivate();
        } else {
            Assert.fail("Unsupported key algorithm: " + originalPrivateKey.getAlgorithm());
            result = null;
        }
    } catch (GeneralSecurityException e) {
        Assert.fail("Failed to generate private key: " + e);
        result = null;
    }
    return result;
}
Also used : DSAPrivateKeySpec(java.security.spec.DSAPrivateKeySpec) DSAParameterSpec(java.security.spec.DSAParameterSpec) PrivateKey(java.security.PrivateKey) RSAPrivateKeySpec(java.security.spec.RSAPrivateKeySpec) GeneralSecurityException(java.security.GeneralSecurityException) KeyPairGenerator(java.security.KeyPairGenerator) KeyFactory(java.security.KeyFactory)

Example 42 with PrivateKey

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

the class ClientHandshakeImpl method processServerHelloDone.

/**
     * Processes ServerHelloDone: makes verification of the server messages; sends
     * client messages, computers masterSecret, sends ChangeCipherSpec
     */
void processServerHelloDone() {
    PrivateKey clientKey = null;
    if (serverCert != null) {
        if (session.cipherSuite.isAnonymous()) {
            unexpectedMessage();
            return;
        }
        verifyServerCert();
    } else {
        if (!session.cipherSuite.isAnonymous()) {
            unexpectedMessage();
            return;
        }
    }
    // Client certificate
    if (certificateRequest != null) {
        X509Certificate[] certs = null;
        // obtain certificates from key manager
        String alias = null;
        String[] certTypes = certificateRequest.getTypesAsString();
        X500Principal[] issuers = certificateRequest.certificate_authorities;
        X509KeyManager km = parameters.getKeyManager();
        if (km instanceof X509ExtendedKeyManager) {
            X509ExtendedKeyManager ekm = (X509ExtendedKeyManager) km;
            if (this.socketOwner != null) {
                alias = ekm.chooseClientAlias(certTypes, issuers, this.socketOwner);
            } else {
                alias = ekm.chooseEngineClientAlias(certTypes, issuers, this.engineOwner);
            }
            if (alias != null) {
                certs = ekm.getCertificateChain(alias);
            }
        } else {
            alias = km.chooseClientAlias(certTypes, issuers, this.socketOwner);
            if (alias != null) {
                certs = km.getCertificateChain(alias);
            }
        }
        session.localCertificates = certs;
        clientCert = new CertificateMessage(certs);
        clientKey = km.getPrivateKey(alias);
        send(clientCert);
    }
    // Client key exchange
    if (session.cipherSuite.keyExchange == CipherSuite.KEY_EXCHANGE_RSA || session.cipherSuite.keyExchange == CipherSuite.KEY_EXCHANGE_RSA_EXPORT) {
        // RSA encrypted premaster secret message
        Cipher c;
        try {
            c = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            if (serverKeyExchange != null) {
                if (!session.cipherSuite.isAnonymous()) {
                    DigitalSignature ds = new DigitalSignature(serverCert.getAuthType());
                    ds.init(serverCert.certs[0]);
                    ds.update(clientHello.getRandom());
                    ds.update(serverHello.getRandom());
                    if (!serverKeyExchange.verifySignature(ds)) {
                        fatalAlert(AlertProtocol.DECRYPT_ERROR, "Cannot verify RSA params");
                        return;
                    }
                }
                c.init(Cipher.WRAP_MODE, serverKeyExchange.getRSAPublicKey());
            } else {
                c.init(Cipher.WRAP_MODE, serverCert.certs[0]);
            }
        } catch (Exception e) {
            fatalAlert(AlertProtocol.INTERNAL_ERROR, "Unexpected exception", e);
            return;
        }
        preMasterSecret = new byte[48];
        parameters.getSecureRandom().nextBytes(preMasterSecret);
        System.arraycopy(clientHello.client_version, 0, preMasterSecret, 0, 2);
        try {
            clientKeyExchange = new ClientKeyExchange(c.wrap(new SecretKeySpec(preMasterSecret, "preMasterSecret")), serverHello.server_version[1] == 1);
        } catch (Exception e) {
            fatalAlert(AlertProtocol.INTERNAL_ERROR, "Unexpected exception", e);
            return;
        }
    } else if (session.cipherSuite.keyExchange == CipherSuite.KEY_EXCHANGE_DHE_DSS || session.cipherSuite.keyExchange == CipherSuite.KEY_EXCHANGE_DHE_DSS_EXPORT || session.cipherSuite.keyExchange == CipherSuite.KEY_EXCHANGE_DHE_RSA || session.cipherSuite.keyExchange == CipherSuite.KEY_EXCHANGE_DHE_RSA_EXPORT || session.cipherSuite.keyExchange == CipherSuite.KEY_EXCHANGE_DH_anon || session.cipherSuite.keyExchange == CipherSuite.KEY_EXCHANGE_DH_anon_EXPORT) {
        /*
             * All other key exchanges should have had a DH key communicated via
             * ServerKeyExchange beforehand.
             */
        if (serverKeyExchange == null) {
            fatalAlert(AlertProtocol.UNEXPECTED_MESSAGE, "Expected ServerKeyExchange");
            return;
        }
        if (session.cipherSuite.isAnonymous() != serverKeyExchange.isAnonymous()) {
            fatalAlert(AlertProtocol.DECRYPT_ERROR, "Wrong type in ServerKeyExchange");
            return;
        }
        try {
            if (!session.cipherSuite.isAnonymous()) {
                DigitalSignature ds = new DigitalSignature(serverCert.getAuthType());
                ds.init(serverCert.certs[0]);
                ds.update(clientHello.getRandom());
                ds.update(serverHello.getRandom());
                if (!serverKeyExchange.verifySignature(ds)) {
                    fatalAlert(AlertProtocol.DECRYPT_ERROR, "Cannot verify DH params");
                    return;
                }
            }
            KeyFactory kf = KeyFactory.getInstance("DH");
            KeyAgreement agreement = KeyAgreement.getInstance("DH");
            KeyPairGenerator kpg = KeyPairGenerator.getInstance("DH");
            PublicKey serverDhPublic = kf.generatePublic(new DHPublicKeySpec(serverKeyExchange.par3, serverKeyExchange.par1, serverKeyExchange.par2));
            DHParameterSpec spec = new DHParameterSpec(serverKeyExchange.par1, serverKeyExchange.par2);
            kpg.initialize(spec);
            KeyPair kp = kpg.generateKeyPair();
            DHPublicKey pubDhKey = (DHPublicKey) kp.getPublic();
            clientKeyExchange = new ClientKeyExchange(pubDhKey.getY());
            PrivateKey privDhKey = kp.getPrivate();
            agreement.init(privDhKey);
            agreement.doPhase(serverDhPublic, true);
            preMasterSecret = agreement.generateSecret();
        } catch (Exception e) {
            fatalAlert(AlertProtocol.INTERNAL_ERROR, "Unexpected exception", e);
            return;
        }
    } else {
        fatalAlert(AlertProtocol.DECRYPT_ERROR, "Unsupported handshake type");
        return;
    }
    if (clientKeyExchange != null) {
        send(clientKeyExchange);
    }
    computerMasterSecret();
    // fixed DH parameters
    if (clientCert != null && clientCert.certs.length > 0 && !clientKeyExchange.isEmpty()) {
        // Certificate verify
        String authType = clientKey.getAlgorithm();
        DigitalSignature ds = new DigitalSignature(authType);
        ds.init(clientKey);
        if ("RSA".equals(authType)) {
            ds.setMD5(io_stream.getDigestMD5());
            ds.setSHA(io_stream.getDigestSHA());
        } else if ("DSA".equals(authType)) {
            ds.setSHA(io_stream.getDigestSHA());
        // The Signature should be empty in case of anonymous signature algorithm:
        // } else if ("DH".equals(authType)) {
        }
        certificateVerify = new CertificateVerify(ds.sign());
        send(certificateVerify);
    }
    sendChangeCipherSpec();
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) DHPublicKey(javax.crypto.interfaces.DHPublicKey) PublicKey(java.security.PublicKey) DHPublicKey(javax.crypto.interfaces.DHPublicKey) DHParameterSpec(javax.crypto.spec.DHParameterSpec) KeyPairGenerator(java.security.KeyPairGenerator) X509ExtendedKeyManager(javax.net.ssl.X509ExtendedKeyManager) X509Certificate(java.security.cert.X509Certificate) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SecretKeySpec(javax.crypto.spec.SecretKeySpec) X509KeyManager(javax.net.ssl.X509KeyManager) X500Principal(javax.security.auth.x500.X500Principal) Cipher(javax.crypto.Cipher) DHPublicKeySpec(javax.crypto.spec.DHPublicKeySpec) KeyAgreement(javax.crypto.KeyAgreement) KeyFactory(java.security.KeyFactory)

Example 43 with PrivateKey

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

the class OpenSSLServerSocketImpl method checkForPrivateKey.

private boolean checkForPrivateKey(String keyType, Class<?> keyClass) {
    String alias = sslParameters.getKeyManager().chooseServerAlias(keyType, null, null);
    if (alias == null) {
        return false;
    }
    PrivateKey key = sslParameters.getKeyManager().getPrivateKey(alias);
    return (key != null && keyClass.isAssignableFrom(key.getClass()));
}
Also used : PrivateKey(java.security.PrivateKey) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) ECPrivateKey(java.security.interfaces.ECPrivateKey) RSAPrivateKey(java.security.interfaces.RSAPrivateKey)

Example 44 with PrivateKey

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

the class OpenSSLSocketImpl method setCertificate.

private void setCertificate(String alias) throws CertificateEncodingException, SSLException {
    if (alias == null) {
        return;
    }
    PrivateKey privateKey = sslParameters.getKeyManager().getPrivateKey(alias);
    if (privateKey == null) {
        return;
    }
    X509Certificate[] certificates = sslParameters.getKeyManager().getCertificateChain(alias);
    if (certificates == null) {
        return;
    }
    // Note that OpenSSL says to use SSL_use_certificate before SSL_use_PrivateKey.
    byte[][] certificateBytes = NativeCrypto.encodeCertificates(certificates);
    NativeCrypto.SSL_use_certificate(sslNativePointer, certificateBytes);
    try {
        final OpenSSLKey key = OpenSSLKey.fromPrivateKey(privateKey);
        NativeCrypto.SSL_use_PrivateKey(sslNativePointer, key.getPkeyContext());
    } catch (InvalidKeyException e) {
        throw new SSLException(e);
    }
    // checks the last installed private key and certificate,
    // so need to do this once per loop iteration
    NativeCrypto.SSL_check_private_key(sslNativePointer);
}
Also used : PrivateKey(java.security.PrivateKey) InvalidKeyException(java.security.InvalidKeyException) SSLException(javax.net.ssl.SSLException) X509Certificate(java.security.cert.X509Certificate)

Example 45 with PrivateKey

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

the class OpenSSLECKeyFactory method engineTranslateKey.

@Override
protected Key engineTranslateKey(Key key) throws InvalidKeyException {
    if (key == null) {
        throw new InvalidKeyException("key == null");
    }
    if ((key instanceof OpenSSLECPublicKey) || (key instanceof OpenSSLECPrivateKey)) {
        return key;
    } else if (key instanceof ECPublicKey) {
        ECPublicKey ecKey = (ECPublicKey) key;
        ECPoint w = ecKey.getW();
        ECParameterSpec params = ecKey.getParams();
        try {
            return engineGeneratePublic(new ECPublicKeySpec(w, params));
        } catch (InvalidKeySpecException e) {
            throw new InvalidKeyException(e);
        }
    } else if (key instanceof ECPrivateKey) {
        ECPrivateKey ecKey = (ECPrivateKey) key;
        BigInteger s = ecKey.getS();
        ECParameterSpec params = ecKey.getParams();
        try {
            return engineGeneratePrivate(new ECPrivateKeySpec(s, params));
        } catch (InvalidKeySpecException e) {
            throw new InvalidKeyException(e);
        }
    } else if ((key instanceof PrivateKey) && ("PKCS#8".equals(key.getFormat()))) {
        byte[] encoded = key.getEncoded();
        if (encoded == null) {
            throw new InvalidKeyException("Key does not support encoding");
        }
        try {
            return engineGeneratePrivate(new PKCS8EncodedKeySpec(encoded));
        } catch (InvalidKeySpecException e) {
            throw new InvalidKeyException(e);
        }
    } else if ((key instanceof PublicKey) && ("X.509".equals(key.getFormat()))) {
        byte[] encoded = key.getEncoded();
        if (encoded == null) {
            throw new InvalidKeyException("Key does not support encoding");
        }
        try {
            return engineGeneratePublic(new X509EncodedKeySpec(encoded));
        } catch (InvalidKeySpecException e) {
            throw new InvalidKeyException(e);
        }
    } else {
        throw new InvalidKeyException("Key must be EC public or private key; was " + key.getClass().getName());
    }
}
Also used : ECPrivateKey(java.security.interfaces.ECPrivateKey) ECPrivateKeySpec(java.security.spec.ECPrivateKeySpec) PrivateKey(java.security.PrivateKey) ECPrivateKey(java.security.interfaces.ECPrivateKey) PublicKey(java.security.PublicKey) ECPublicKey(java.security.interfaces.ECPublicKey) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) InvalidKeyException(java.security.InvalidKeyException) ECPoint(java.security.spec.ECPoint) ECPublicKeySpec(java.security.spec.ECPublicKeySpec) ECPublicKey(java.security.interfaces.ECPublicKey) ECParameterSpec(java.security.spec.ECParameterSpec) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) BigInteger(java.math.BigInteger) InvalidKeySpecException(java.security.spec.InvalidKeySpecException)

Aggregations

PrivateKey (java.security.PrivateKey)517 X509Certificate (java.security.cert.X509Certificate)217 KeyFactory (java.security.KeyFactory)169 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)144 Certificate (java.security.cert.Certificate)127 PublicKey (java.security.PublicKey)120 ByteArrayInputStream (java.io.ByteArrayInputStream)118 KeyStore (java.security.KeyStore)93 CertificateFactory (java.security.cert.CertificateFactory)92 IOException (java.io.IOException)81 Key (java.security.Key)74 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)73 PrivateKeyEntry (java.security.KeyStore.PrivateKeyEntry)70 Entry (java.security.KeyStore.Entry)60 TrustedCertificateEntry (java.security.KeyStore.TrustedCertificateEntry)60 KeyPair (java.security.KeyPair)59 SecretKey (javax.crypto.SecretKey)48 InvalidKeyException (java.security.InvalidKeyException)47 KeyStoreException (java.security.KeyStoreException)46 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)46