Search in sources :

Example 16 with KeyAgreement

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

the class ECDHKeyAgreementTest method testInit_withUnsupportedPrivateKeyType.

void testInit_withUnsupportedPrivateKeyType(Provider provider) throws Exception {
    KeyAgreement keyAgreement = getKeyAgreement(provider);
    try {
        keyAgreement.init(KAT_PUBLIC_KEY1);
        fail();
    } catch (InvalidKeyException expected) {
    }
}
Also used : KeyAgreement(javax.crypto.KeyAgreement) InvalidKeyException(java.security.InvalidKeyException)

Example 17 with KeyAgreement

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

the class ECDHKeyAgreementTest method testGenerateSecret_withLargerThatNeededBuffer.

void testGenerateSecret_withLargerThatNeededBuffer(Provider provider) throws Exception {
    KeyAgreement keyAgreement = getKeyAgreement(provider);
    keyAgreement.init(KAT_PRIVATE_KEY1);
    keyAgreement.doPhase(KAT_PUBLIC_KEY2, true);
    // Place the shared secret in the middle of the larger buffer and check that only that
    // part of the buffer is affected.
    byte[] buffer = new byte[KAT_SECRET.length + 2];
    // arbitrary canary value
    buffer[0] = (byte) 0x85;
    // arbitrary canary value
    buffer[buffer.length - 1] = (byte) 0x3b;
    int secretLengthBytes = keyAgreement.generateSecret(buffer, 1);
    assertEquals(KAT_SECRET.length, secretLengthBytes);
    assertEquals((byte) 0x85, buffer[0]);
    assertEquals((byte) 0x3b, buffer[buffer.length - 1]);
    byte[] secret = new byte[KAT_SECRET.length];
    System.arraycopy(buffer, 1, secret, 0, secret.length);
    assertTrue(Arrays.equals(KAT_SECRET, secret));
}
Also used : KeyAgreement(javax.crypto.KeyAgreement)

Example 18 with KeyAgreement

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

the class ServerHandshakeImpl method unwrap.

/**
     * Proceses inbound handshake messages
     * @param bytes
     */
@Override
public void unwrap(byte[] bytes) {
    io_stream.append(bytes);
    while (io_stream.available() > 0) {
        int handshakeType;
        int length;
        io_stream.mark();
        try {
            handshakeType = io_stream.read();
            length = io_stream.readUint24();
            if (io_stream.available() < length) {
                io_stream.reset();
                return;
            }
            switch(handshakeType) {
                case // CLIENT_HELLO
                1:
                    if (clientHello != null && this.status != FINISHED) {
                        // Client hello has been received during handshake
                        unexpectedMessage();
                        return;
                    }
                    // if protocol planed to send Hello Request message
                    // - cancel this demand.
                    needSendHelloRequest = false;
                    clientHello = new ClientHello(io_stream, length);
                    if (nonBlocking) {
                        delegatedTasks.add(new DelegatedTask(new Runnable() {

                            public void run() {
                                processClientHello();
                            }
                        }, this));
                        return;
                    }
                    processClientHello();
                    break;
                case //    CLIENT CERTIFICATE
                11:
                    if (isResuming || certificateRequest == null || serverHelloDone == null || clientCert != null) {
                        unexpectedMessage();
                        return;
                    }
                    clientCert = new CertificateMessage(io_stream, length);
                    if (clientCert.certs.length == 0) {
                        if (parameters.getNeedClientAuth()) {
                            fatalAlert(AlertProtocol.HANDSHAKE_FAILURE, "HANDSHAKE FAILURE: no client certificate received");
                        }
                    } else {
                        String authType = clientCert.getAuthType();
                        try {
                            parameters.getTrustManager().checkClientTrusted(clientCert.certs, authType);
                        } catch (CertificateException e) {
                            fatalAlert(AlertProtocol.BAD_CERTIFICATE, "Untrusted Client Certificate ", e);
                        }
                        session.peerCertificates = clientCert.certs;
                    }
                    break;
                case // CERTIFICATE_VERIFY
                15:
                    if (isResuming || clientKeyExchange == null || clientCert == null || //client certificate
                    clientKeyExchange.isEmpty() || // parameters
                    certificateVerify != null || changeCipherSpecReceived) {
                        unexpectedMessage();
                        return;
                    }
                    certificateVerify = new CertificateVerify(io_stream, length);
                    String authType = clientCert.getAuthType();
                    DigitalSignature ds = new DigitalSignature(authType);
                    ds.init(clientCert.certs[0]);
                    byte[] md5_hash = null;
                    byte[] sha_hash = null;
                    if ("RSA".equals(authType)) {
                        md5_hash = io_stream.getDigestMD5withoutLast();
                        sha_hash = io_stream.getDigestSHAwithoutLast();
                    } else if ("DSA".equals(authType)) {
                        sha_hash = io_stream.getDigestSHAwithoutLast();
                    // The Signature should be empty in case of anonymous signature algorithm:
                    // } else if ("DH".equals(authType)) {
                    }
                    ds.setMD5(md5_hash);
                    ds.setSHA(sha_hash);
                    if (!ds.verifySignature(certificateVerify.signedHash)) {
                        fatalAlert(AlertProtocol.DECRYPT_ERROR, "DECRYPT ERROR: CERTIFICATE_VERIFY incorrect signature");
                    }
                    break;
                case // CLIENT_KEY_EXCHANGE
                16:
                    if (isResuming || serverHelloDone == null || clientKeyExchange != null || (clientCert == null && parameters.getNeedClientAuth())) {
                        unexpectedMessage();
                        return;
                    }
                    if (session.cipherSuite.keyExchange == CipherSuite.KEY_EXCHANGE_RSA || session.cipherSuite.keyExchange == CipherSuite.KEY_EXCHANGE_RSA_EXPORT) {
                        clientKeyExchange = new ClientKeyExchange(io_stream, length, serverHello.server_version[1] == 1, true);
                        Cipher c = null;
                        try {
                            c = Cipher.getInstance("RSA/ECB/PKCS1Padding");
                            c.init(Cipher.UNWRAP_MODE, privKey);
                            preMasterSecret = c.unwrap(clientKeyExchange.exchange_keys, "preMasterSecret", Cipher.SECRET_KEY).getEncoded();
                            // check preMasterSecret:
                            if (preMasterSecret.length != 48 || preMasterSecret[0] != clientHello.client_version[0] || preMasterSecret[1] != clientHello.client_version[1]) {
                                // incorrect preMasterSecret
                                // prevent an attack (see TLS 1.0 spec., 7.4.7.1.)
                                preMasterSecret = new byte[48];
                                parameters.getSecureRandom().nextBytes(preMasterSecret);
                            }
                        } catch (Exception e) {
                            fatalAlert(AlertProtocol.INTERNAL_ERROR, "INTERNAL ERROR", e);
                        }
                    } else {
                        // diffie hellman key exchange
                        clientKeyExchange = new ClientKeyExchange(io_stream, length, serverHello.server_version[1] == 1, false);
                        if (clientKeyExchange.isEmpty()) {
                            // TODO check that client cert. DH params
                            // matched server cert. DH params
                            // client cert. contains fixed DH parameters
                            preMasterSecret = ((DHPublicKey) clientCert.certs[0].getPublicKey()).getY().toByteArray();
                        } else {
                            try {
                                KeyFactory kf = KeyFactory.getInstance("DH");
                                KeyAgreement agreement = KeyAgreement.getInstance("DH");
                                PublicKey clientPublic = kf.generatePublic(new DHPublicKeySpec(new BigInteger(1, clientKeyExchange.exchange_keys), serverKeyExchange.par1, serverKeyExchange.par2));
                                agreement.init(privKey);
                                agreement.doPhase(clientPublic, true);
                                preMasterSecret = agreement.generateSecret();
                            } catch (Exception e) {
                                fatalAlert(AlertProtocol.INTERNAL_ERROR, "INTERNAL ERROR", e);
                                return;
                            }
                        }
                    }
                    computerMasterSecret();
                    break;
                case // FINISHED
                20:
                    if (!isResuming && !changeCipherSpecReceived) {
                        unexpectedMessage();
                        return;
                    }
                    clientFinished = new Finished(io_stream, length);
                    verifyFinished(clientFinished.getData());
                    session.context = parameters.getServerSessionContext();
                    parameters.getServerSessionContext().putSession(session);
                    if (!isResuming) {
                        sendChangeCipherSpec();
                    } else {
                        session.lastAccessedTime = System.currentTimeMillis();
                        status = FINISHED;
                    }
                    break;
                default:
                    unexpectedMessage();
                    return;
            }
        } catch (IOException e) {
            // io stream dosn't contain complete handshake message
            io_stream.reset();
            return;
        }
    }
}
Also used : DHPublicKey(javax.crypto.interfaces.DHPublicKey) PublicKey(java.security.PublicKey) RSAPublicKey(java.security.interfaces.RSAPublicKey) DHPublicKey(javax.crypto.interfaces.DHPublicKey) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) BigInteger(java.math.BigInteger) Cipher(javax.crypto.Cipher) DHPublicKeySpec(javax.crypto.spec.DHPublicKeySpec) KeyAgreement(javax.crypto.KeyAgreement) KeyFactory(java.security.KeyFactory)

Example 19 with KeyAgreement

use of javax.crypto.KeyAgreement in project wycheproof by google.

the class DhTest method testDh.

/** Check that key agreement using DH works. */
@SuppressWarnings("InsecureCryptoUsage")
public void testDh() throws Exception {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DH");
    DHParameterSpec dhparams = ike2048();
    keyGen.initialize(dhparams);
    KeyPair keyPairA = keyGen.generateKeyPair();
    KeyPair keyPairB = keyGen.generateKeyPair();
    KeyAgreement kaA = KeyAgreement.getInstance("DH");
    KeyAgreement kaB = KeyAgreement.getInstance("DH");
    kaA.init(keyPairA.getPrivate());
    kaB.init(keyPairB.getPrivate());
    kaA.doPhase(keyPairB.getPublic(), true);
    kaB.doPhase(keyPairA.getPublic(), true);
    byte[] kAB = kaA.generateSecret();
    byte[] kBA = kaB.generateSecret();
    assertEquals(TestUtil.bytesToHex(kAB), TestUtil.bytesToHex(kBA));
}
Also used : KeyPair(java.security.KeyPair) DHParameterSpec(javax.crypto.spec.DHParameterSpec) KeyPairGenerator(java.security.KeyPairGenerator) KeyAgreement(javax.crypto.KeyAgreement)

Example 20 with KeyAgreement

use of javax.crypto.KeyAgreement in project wycheproof by google.

the class DhTest method testDHDistinctParameters.

/** This test tries a key agreement with keys using distinct parameters. */
@SuppressWarnings("InsecureCryptoUsage")
public void testDHDistinctParameters() throws Exception {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DH");
    keyGen.initialize(ike1536());
    KeyPair keyPairA = keyGen.generateKeyPair();
    keyGen.initialize(ike2048());
    KeyPair keyPairB = keyGen.generateKeyPair();
    KeyAgreement kaA = KeyAgreement.getInstance("DH");
    kaA.init(keyPairA.getPrivate());
    try {
        kaA.doPhase(keyPairB.getPublic(), true);
        byte[] kAB = kaA.generateSecret();
        fail("Generated secrets with mixed keys " + TestUtil.bytesToHex(kAB) + ", ");
    } catch (java.security.GeneralSecurityException ex) {
    // This is expected.
    }
}
Also used : KeyPair(java.security.KeyPair) GeneralSecurityException(java.security.GeneralSecurityException) KeyPairGenerator(java.security.KeyPairGenerator) 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