Search in sources :

Example 1 with DHParameterSpec

use of javax.crypto.spec.DHParameterSpec in project robovm by robovm.

the class JCEDHPrivateKey method readObject.

private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    x = (BigInteger) in.readObject();
    this.dhSpec = new DHParameterSpec((BigInteger) in.readObject(), (BigInteger) in.readObject(), in.readInt());
}
Also used : BigInteger(java.math.BigInteger) DHParameterSpec(javax.crypto.spec.DHParameterSpec)

Example 2 with DHParameterSpec

use of javax.crypto.spec.DHParameterSpec in project robovm by robovm.

the class JCEDHPublicKey method readObject.

private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    this.y = (BigInteger) in.readObject();
    this.dhSpec = new DHParameterSpec((BigInteger) in.readObject(), (BigInteger) in.readObject(), in.readInt());
}
Also used : BigInteger(java.math.BigInteger) DHParameterSpec(javax.crypto.spec.DHParameterSpec)

Example 3 with DHParameterSpec

use of javax.crypto.spec.DHParameterSpec 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 4 with DHParameterSpec

use of javax.crypto.spec.DHParameterSpec in project robovm by robovm.

the class KeyAgreementTest method testInit04.

/**
     * Test for the methods:
     * <code>init(Key key, AlgorithmParameterSpec params)</code>
     * <code>init(Key key, AlgorithmParameterSpec params, SecureRandom random)</code>
     * <code>generateSecret()</code>
     * Assertions: initializes KeyAgreement and returns byte array
     */
public void testInit04() throws Exception, InvalidAlgorithmParameterException {
    if (!DEFSupported) {
        fail(NotSupportMsg);
        return;
    }
    createKeys();
    KeyAgreement[] kAgs = createKAs();
    DHParameterSpec dhPs = ((DHPrivateKey) privKey).getParams();
    AlgorithmParameterSpec aps = new RSAKeyGenParameterSpec(10, new BigInteger("10"));
    byte[] bbRes1;
    byte[] bbRes2;
    byte[] bbRes3;
    SecureRandom randomNull = null;
    SecureRandom random = new SecureRandom();
    for (int i = 0; i < kAgs.length; i++) {
        kAgs[i].init(privKey, dhPs);
        kAgs[i].doPhase(publKey, true);
        bbRes1 = kAgs[i].generateSecret();
        kAgs[i].init(privKey, dhPs, random);
        kAgs[i].doPhase(publKey, true);
        bbRes2 = kAgs[i].generateSecret();
        assertEquals("Incorrect byte array length", bbRes1.length, bbRes2.length);
        for (int j = 0; j < bbRes1.length; j++) {
            assertEquals("Incorrect byte (index: ".concat(Integer.toString(i)).concat(")"), bbRes1[j], bbRes2[j]);
        }
        kAgs[i].init(privKey, dhPs, randomNull);
        kAgs[i].doPhase(publKey, true);
        bbRes3 = kAgs[i].generateSecret();
        assertEquals("Incorrect byte array length", bbRes1.length, bbRes3.length);
        for (int j = 0; j < bbRes1.length; j++) {
            assertEquals("Incorrect byte (index: ".concat(Integer.toString(i)).concat(")"), bbRes1[j], bbRes3[j]);
        }
        try {
            kAgs[i].init(publKey, dhPs, random);
            fail("InvalidKeyException expected");
        } catch (InvalidKeyException e) {
        //expected
        }
        try {
            kAgs[i].init(privKey, aps, random);
            fail("InvalidAlgorithmParameterException expected");
        } catch (InvalidAlgorithmParameterException e) {
        //expected
        }
    }
}
Also used : DHPrivateKey(javax.crypto.interfaces.DHPrivateKey) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) RSAKeyGenParameterSpec(java.security.spec.RSAKeyGenParameterSpec) BigInteger(java.math.BigInteger) SecureRandom(java.security.SecureRandom) DHParameterSpec(javax.crypto.spec.DHParameterSpec) KeyAgreement(javax.crypto.KeyAgreement) InvalidKeyException(java.security.InvalidKeyException) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec)

Example 5 with DHParameterSpec

use of javax.crypto.spec.DHParameterSpec in project robovm by robovm.

the class OldDHTest method testDHGen.

@BrokenTest("Suffers from DH slowness, disabling for now")
public void testDHGen() throws Exception {
    KeyPairGenerator gen = null;
    try {
        gen = KeyPairGenerator.getInstance("DH");
    } catch (NoSuchAlgorithmException e) {
        fail(e.getMessage());
    }
    AlgorithmParameterGenerator algorithmparametergenerator = AlgorithmParameterGenerator.getInstance("DH");
    algorithmparametergenerator.init(1024, new SecureRandom());
    AlgorithmParameters algorithmparameters = algorithmparametergenerator.generateParameters();
    DHParameterSpec dhparameterspec = algorithmparameters.getParameterSpec(DHParameterSpec.class);
    //gen.initialize(1024);
    gen.initialize(dhparameterspec);
    KeyPair key = gen.generateKeyPair();
}
Also used : KeyPair(java.security.KeyPair) AlgorithmParameterGenerator(java.security.AlgorithmParameterGenerator) SecureRandom(java.security.SecureRandom) DHParameterSpec(javax.crypto.spec.DHParameterSpec) KeyPairGenerator(java.security.KeyPairGenerator) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) AlgorithmParameters(java.security.AlgorithmParameters) BrokenTest(dalvik.annotation.BrokenTest)

Aggregations

DHParameterSpec (javax.crypto.spec.DHParameterSpec)44 BigInteger (java.math.BigInteger)18 KeyPair (java.security.KeyPair)13 KeyPairGenerator (java.security.KeyPairGenerator)13 KeyAgreement (javax.crypto.KeyAgreement)10 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)7 SecureRandom (java.security.SecureRandom)7 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)6 InvalidKeyException (java.security.InvalidKeyException)6 KeyFactory (java.security.KeyFactory)6 PublicKey (java.security.PublicKey)6 DHPrivateKey (javax.crypto.interfaces.DHPrivateKey)6 DHPublicKeySpec (javax.crypto.spec.DHPublicKeySpec)6 DHPublicKey (javax.crypto.interfaces.DHPublicKey)5 IOException (java.io.IOException)4 PrivateKey (java.security.PrivateKey)4 CertificateException (java.security.cert.CertificateException)4 X509Certificate (java.security.cert.X509Certificate)4 X509ExtendedKeyManager (javax.net.ssl.X509ExtendedKeyManager)4 X509KeyManager (javax.net.ssl.X509KeyManager)4