Search in sources :

Example 1 with KeyAgreement

use of javax.crypto.KeyAgreement in project robovm by robovm.

the class AlgorithmParameterKeyAgreementHelper method test.

@Override
public void test(AlgorithmParameters parameters) {
    KeyPairGenerator generator = null;
    try {
        generator = KeyPairGenerator.getInstance(algorithmName);
    } catch (NoSuchAlgorithmException e) {
        Assert.fail(e.getMessage());
    }
    generator.initialize(1024);
    KeyPair keyPair = generator.generateKeyPair();
    KeyAgreement keyAgreement = null;
    try {
        keyAgreement = KeyAgreement.getInstance(algorithmName);
    } catch (NoSuchAlgorithmException e) {
        Assert.fail(e.getMessage());
    }
    try {
        keyAgreement.init(keyPair.getPrivate());
    } catch (InvalidKeyException e) {
        Assert.fail(e.getMessage());
    }
    try {
        keyAgreement.doPhase(keyPair.getPublic(), true);
    } catch (InvalidKeyException e) {
        Assert.fail(e.getMessage());
    } catch (IllegalStateException e) {
        Assert.fail(e.getMessage());
    }
    Assert.assertNotNull("generated secret is null", keyAgreement.generateSecret());
}
Also used : KeyPair(java.security.KeyPair) KeyPairGenerator(java.security.KeyPairGenerator) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyAgreement(javax.crypto.KeyAgreement) InvalidKeyException(java.security.InvalidKeyException)

Example 2 with KeyAgreement

use of javax.crypto.KeyAgreement in project robovm by robovm.

the class KeyAgreementHelper method test.

void test(PrivateKey encryptKey, PublicKey decryptKey) {
    KeyAgreement keyAgreement = null;
    try {
        keyAgreement = KeyAgreement.getInstance(algorithmName);
    } catch (NoSuchAlgorithmException e) {
        Assert.fail(e.getMessage());
    }
    try {
        keyAgreement.init(encryptKey);
    } catch (InvalidKeyException e) {
        Assert.fail(e.getMessage());
    }
    try {
        keyAgreement.doPhase(decryptKey, true);
    } catch (InvalidKeyException e) {
        Assert.fail(e.getMessage());
    } catch (IllegalStateException e) {
        Assert.fail(e.getMessage());
    }
    Assert.assertNotNull("generated secret is null", keyAgreement.generateSecret());
}
Also used : NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyAgreement(javax.crypto.KeyAgreement) InvalidKeyException(java.security.InvalidKeyException)

Example 3 with KeyAgreement

use of javax.crypto.KeyAgreement 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 KeyAgreement

use of javax.crypto.KeyAgreement in project robovm by robovm.

the class KeyAgreementTest method testInit03.

/**
     * Test for the methods: <code>init(Key key)</code>
     * <code>init(Key key, SecureRandom random)</code>
     * <code>generateSecret()</code>
     * Assertions: initializes KeyAgreement and returns byte array
     */
public void testInit03() throws Exception {
    if (!DEFSupported) {
        fail(NotSupportMsg);
        return;
    }
    createKeys();
    KeyAgreement[] kAgs = createKAs();
    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);
        kAgs[i].doPhase(publKey, true);
        bbRes1 = kAgs[i].generateSecret();
        kAgs[i].init(privKey, 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, 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]);
        }
    }
}
Also used : SecureRandom(java.security.SecureRandom) KeyAgreement(javax.crypto.KeyAgreement)

Example 5 with KeyAgreement

use of javax.crypto.KeyAgreement in project robovm by robovm.

the class KeyAgreementTest method testGetInstanceStringString03.

/**
     * Test for <code> getInstance(String algorithm, String provider)</code>
     * method Assertions: returns KeyAgreement object
     */
public void testGetInstanceStringString03() throws IllegalArgumentException, NoSuchAlgorithmException, NoSuchProviderException {
    if (!DEFSupported) {
        fail(NotSupportMsg);
        return;
    }
    KeyAgreement keyA;
    for (int i = 0; i < validValues.length; i++) {
        keyA = KeyAgreement.getInstance(validValues[i], defaultProviderName);
        assertEquals("Incorrect algorithm", keyA.getAlgorithm(), validValues[i]);
        assertEquals("Incorrect provider", keyA.getProvider().getName(), defaultProviderName);
    }
}
Also used : KeyAgreement(javax.crypto.KeyAgreement)

Aggregations

KeyAgreement (javax.crypto.KeyAgreement)55 KeyPairGenerator (java.security.KeyPairGenerator)15 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)14 InvalidKeyException (java.security.InvalidKeyException)12 KeyFactory (java.security.KeyFactory)12 SecretKey (javax.crypto.SecretKey)10 DHParameterSpec (javax.crypto.spec.DHParameterSpec)10 KeyPair (java.security.KeyPair)9 Cipher (javax.crypto.Cipher)9 IOException (java.io.IOException)7 PublicKey (java.security.PublicKey)7 BigInteger (java.math.BigInteger)6 SecureRandom (java.security.SecureRandom)6 DHPublicKey (javax.crypto.interfaces.DHPublicKey)6 SecretKeySpec (javax.crypto.spec.SecretKeySpec)6 GeneralSecurityException (java.security.GeneralSecurityException)5 DHPublicKeySpec (javax.crypto.spec.DHPublicKeySpec)5 IvParameterSpec (javax.crypto.spec.IvParameterSpec)5 PrivateKey (java.security.PrivateKey)4 CertificateException (java.security.cert.CertificateException)4