Search in sources :

Example 31 with SecretKeySpec

use of javax.crypto.spec.SecretKeySpec 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 32 with SecretKeySpec

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

the class MacTest method test_getInstance_OpenSSL_ENGINE.

public void test_getInstance_OpenSSL_ENGINE() throws Exception {
    final String secret = "-HMAC-test1";
    final byte[] testString = "testing123".getBytes();
    Provider p = Security.getProvider(OpenSSLProvider.PROVIDER_NAME);
    NativeCryptoTest.loadTestEngine();
    OpenSSLEngine engine = OpenSSLEngine.getInstance(NativeCryptoTest.TEST_ENGINE_ID);
    /*
         * The "-HMAC-" prefix is a special prefix recognized by
         * test_openssl_engine.cpp
         */
    SecretKey key1 = engine.getSecretKeyById(secret, "HmacSHA256");
    SecretKey key1dupe = engine.getSecretKeyById(secret, "HmacSHA256");
    /* Non-ENGINE-based SecretKey */
    SecretKey key2 = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
    /* The one that is ENGINE-based can't be equal to a non-ENGINE one. */
    assertFalse(key1.equals(key2));
    assertEquals(key1, key1dupe);
    assertNull(key1.getFormat());
    assertNull(key1.getEncoded());
    assertEquals("RAW", key2.getFormat());
    assertEquals(Arrays.toString(secret.getBytes()), Arrays.toString(key2.getEncoded()));
    Mac mac1 = Mac.getInstance("HmacSHA256", p);
    mac1.init(key1);
    mac1.update(testString);
    byte[] output1 = mac1.doFinal();
    assertEquals(mac1.getMacLength(), output1.length);
    Mac mac2 = Mac.getInstance("HmacSHA256", p);
    mac2.init(key2);
    mac2.update(testString);
    byte[] output2 = mac2.doFinal();
    assertEquals(Arrays.toString(output2), Arrays.toString(output1));
}
Also used : SecretKey(javax.crypto.SecretKey) SecretKeySpec(javax.crypto.spec.SecretKeySpec) Mac(javax.crypto.Mac) Provider(java.security.Provider)

Example 33 with SecretKeySpec

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

the class MyMacSpi2 method testMacSpiTests01.

/**
     * Test for <code>MacSpi</code> constructor
     * Assertion: constructs MacSpi
     */
public void testMacSpiTests01() throws Exception {
    Mock_MacSpi mSpi = new Mock_MacSpi();
    byte[] bb1 = { (byte) 1, (byte) 2, (byte) 3, (byte) 4, (byte) 5 };
    SecretKeySpec sks = new SecretKeySpec(bb1, "SHA1");
    assertEquals("Incorrect MacLength", mSpi.engineGetMacLength(), 0);
    try {
        mSpi.engineInit(null, null);
        fail("IllegalArgumentException must be thrown");
    } catch (IllegalArgumentException e) {
    }
    mSpi.engineInit(sks, null);
    byte[] bb = mSpi.engineDoFinal();
    assertEquals(bb.length, 0);
    try {
        mSpi.clone();
        fail("CloneNotSupportedException was not thrown as expected");
    } catch (CloneNotSupportedException e) {
    }
    Mock_MacSpi1 mSpi1 = new Mock_MacSpi1();
    mSpi1.clone();
    byte[] bbb = new byte[10];
    for (int i = 0; i < bbb.length; i++) {
        bbb[i] = (byte) i;
    }
    try {
        mSpi1.engineInit(null, null);
        fail("IllegalArgumentException must be thrown");
    } catch (IllegalArgumentException e) {
    }
    mSpi1.engineInit(sks, null);
    ByteBuffer byteBuf = ByteBuffer.allocate(10);
    byteBuf.put(bbb);
    byteBuf.position(5);
    int beforeUp = byteBuf.remaining();
    mSpi1.engineUpdate(byteBuf);
    bb = mSpi1.engineDoFinal();
    assertEquals("Incorrect result of engineDoFinal", bb.length, beforeUp);
    Mock_MacSpi2 mSpi2 = new Mock_MacSpi2();
    mSpi2.engineInit(null, null);
    mSpi2.engineInit(sks, null);
    try {
        mSpi2.clone();
    } catch (CloneNotSupportedException e) {
    }
    byte[] bbuf = { (byte) 5, (byte) 4, (byte) 3, (byte) 2, (byte) 1 };
    byteBuf = ByteBuffer.allocate(5);
    byteBuf.put(bbuf);
    byteBuf.position(5);
    if (!byteBuf.hasRemaining()) {
        mSpi2.engineUpdate(byteBuf);
    }
}
Also used : SecretKeySpec(javax.crypto.spec.SecretKeySpec) ByteBuffer(java.nio.ByteBuffer)

Example 34 with SecretKeySpec

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

the class myMac method testUpdateByteBuffer02.

/**
     * Test for <code>update(ByteBuffer input)</code>
     * <code>update(byte[] input, int offset, int len)</code>
     * methods
     * Assertion: processes Mac
     */
public void testUpdateByteBuffer02() throws NoSuchAlgorithmException, NoSuchProviderException, IllegalArgumentException, IllegalStateException, InvalidAlgorithmParameterException, InvalidKeyException {
    if (!DEFSupported) {
        fail(NotSupportedMsg);
        return;
    }
    Mac[] macs = createMacs();
    assertNotNull("Mac objects were not created", macs);
    byte[] bb = { (byte) 1, (byte) 2, (byte) 3, (byte) 4, (byte) 5 };
    SecretKeySpec sks = new SecretKeySpec(bb, "SHA1");
    byte[] bbuf = { (byte) 5, (byte) 4, (byte) 3, (byte) 2, (byte) 1 };
    ByteBuffer byteBuf;
    byte[] bb1;
    byte[] bb2;
    for (int i = 0; i < macs.length; i++) {
        byteBuf = ByteBuffer.allocate(5);
        byteBuf.put(bbuf);
        byteBuf.position(2);
        macs[i].init(sks);
        macs[i].update(byteBuf);
        bb1 = macs[i].doFinal();
        macs[i].init(sks);
        macs[i].update(bbuf, 2, 3);
        bb2 = macs[i].doFinal();
        for (int t = 0; t < bb1.length; t++) {
            assertEquals("Incorrect doFinal result", bb1[t], bb2[t]);
        }
    }
}
Also used : SecretKeySpec(javax.crypto.spec.SecretKeySpec) ByteBuffer(java.nio.ByteBuffer) Mac(javax.crypto.Mac)

Example 35 with SecretKeySpec

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

the class myMac method testMac10.

/**
     * Test for <code>doFinal(byte[] output, int outOffset)</code> method
     * Assertion:
     * throws ShotBufferException when outOffset  is negative or
     * outOffset >= output.length  or when given buffer is small
     */
public void testMac10() throws NoSuchAlgorithmException, NoSuchProviderException, IllegalArgumentException, IllegalStateException, InvalidKeyException {
    if (!DEFSupported) {
        fail(NotSupportedMsg);
        return;
    }
    Mac[] macs = createMacs();
    assertNotNull("Mac objects were not created", macs);
    byte[] b = { (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0 };
    byte[] byteA = new byte[b.length];
    SecretKeySpec sks = new SecretKeySpec(b, "SHA1");
    for (int i = 0; i < macs.length; i++) {
        macs[i].init(sks);
        try {
            macs[i].doFinal(null, 10);
            fail("ShortBufferException must be thrown");
        } catch (ShortBufferException e) {
        }
        try {
            macs[i].doFinal(byteA, -4);
            fail("ShortBufferException must be thrown");
        } catch (ShortBufferException e) {
        }
        try {
            macs[i].doFinal(byteA, 10);
            fail("ShortBufferException must be thrown");
        } catch (ShortBufferException e) {
        }
        try {
            macs[i].doFinal(new byte[1], 0);
            fail("ShortBufferException must be thrown");
        } catch (ShortBufferException e) {
        }
        byte[] res = macs[i].doFinal();
        try {
            macs[i].doFinal(new byte[res.length - 1], 0);
            fail("ShortBufferException must be thrown");
        } catch (ShortBufferException e) {
        }
    }
}
Also used : SecretKeySpec(javax.crypto.spec.SecretKeySpec) ShortBufferException(javax.crypto.ShortBufferException) Mac(javax.crypto.Mac)

Aggregations

SecretKeySpec (javax.crypto.spec.SecretKeySpec)498 Cipher (javax.crypto.Cipher)194 SecretKey (javax.crypto.SecretKey)142 Mac (javax.crypto.Mac)110 IvParameterSpec (javax.crypto.spec.IvParameterSpec)106 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)94 InvalidKeyException (java.security.InvalidKeyException)67 IOException (java.io.IOException)44 Key (java.security.Key)36 SecureRandom (java.security.SecureRandom)30 Test (org.junit.Test)30 UnsupportedEncodingException (java.io.UnsupportedEncodingException)29 GeneralSecurityException (java.security.GeneralSecurityException)27 IllegalBlockSizeException (javax.crypto.IllegalBlockSizeException)27 MessageDigest (java.security.MessageDigest)25 BadPaddingException (javax.crypto.BadPaddingException)25 NoSuchPaddingException (javax.crypto.NoSuchPaddingException)25 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)18 PrivateKey (java.security.PrivateKey)18 PublicKey (java.security.PublicKey)16