Search in sources :

Example 6 with DHPublicKeySpec

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

use of javax.crypto.spec.DHPublicKeySpec in project derby by apache.

the class EncryptionManager method generatePrivateKey.

// This method generates a secret key using the application server's
// public key
private byte[] generatePrivateKey(byte[] targetPublicKey) throws SqlException {
    try {
        // initiate a Diffie_Hellman KeyFactory object.
        KeyFactory keyFac = KeyFactory.getInstance("DH", provider);
        // Use server's public key to initiate a DHPublicKeySpec and then use
        // this DHPublicKeySpec to initiate a publicKey object
        BigInteger publicKey = new BigInteger(1, targetPublicKey);
        DHPublicKeySpec dhKeySpec = new DHPublicKeySpec(publicKey, modulus__, base__);
        PublicKey pubKey = keyFac.generatePublic(dhKeySpec);
        // Execute the first phase of DH keyagreement protocal.
        keyAgreement_.doPhase(pubKey, true);
        // generate the shared secret key. The application requestor's shared secret
        // key should be exactly the same as the application server's shared secret
        // key
        byte[] sharedSecret = keyAgreement_.generateSecret();
        byte[] newKey = new byte[32];
        // pad 0 to the beginning of the byte array tho make the secret key 32 bytes.
        if (sharedSecret.length == 33 && sharedSecret[0] == 0) {
            for (int i = 0; i < newKey.length; i++) {
                newKey[i] = sharedSecret[i + 1];
            }
        }
        if (sharedSecret.length < 32) {
            int i;
            for (i = 0; i < (32 - sharedSecret.length); i++) {
                newKey[i] = 0;
            }
            for (int j = i; j < sharedSecret.length; j++) {
                newKey[j] = sharedSecret[j - i];
            }
        }
        // The Data Encryption Standard (DES) is going to be used to encrypt userid
        // and password. DES is a block cipher; it encrypts data in 64-bit blocks.
        // PROTOCOL encryption uses DES CBC mode as defined by the FIPS standard
        // DES CBC requires an encryption key and an 8 byte token to encrypt the data.
        // The middle 8 bytes of Diffie-Hellman shared private key is used as the
        // encryption key. The following code retrieves middle 8 bytes of the shared
        // private key.
        byte[] key = new byte[8];
        // if secret key is not 32, we will use the adjust length secret key
        if (sharedSecret.length == 32) {
            for (int i = 0; i < 8; i++) {
                key[i] = sharedSecret[i + 12];
            }
        } else if (sharedSecret.length == 33 || sharedSecret.length < 32) {
            for (int i = 0; i < 8; i++) {
                key[i] = newKey[i + 12];
            }
        } else {
            throw new SqlException(agent_.logWriter_, new ClientMessageId(SQLState.SHARED_KEY_LENGTH_ERROR), sharedSecret.length);
        }
        // we do parity check here and flip the parity bit if the byte has even number of 1s
        keyParityCheck(key);
        return key;
    } catch (GeneralSecurityException e) {
        throw new SqlException(agent_.logWriter_, new ClientMessageId(SQLState.SECURITY_EXCEPTION_ENCOUNTERED), e);
    }
}
Also used : PublicKey(java.security.PublicKey) DHPublicKey(javax.crypto.interfaces.DHPublicKey) GeneralSecurityException(java.security.GeneralSecurityException) BigInteger(java.math.BigInteger) DHPublicKeySpec(javax.crypto.spec.DHPublicKeySpec) SecretKeyFactory(javax.crypto.SecretKeyFactory) KeyFactory(java.security.KeyFactory)

Example 8 with DHPublicKeySpec

use of javax.crypto.spec.DHPublicKeySpec in project remote-desktop-clients by iiordanov.

the class RFBSecurityARD method performDHKeyAgreement.

private DHResult performDHKeyAgreement(BigInteger prime, BigInteger generator, BigInteger peerKey, int keyLength) throws IOException {
    // fetch instances of all needed Diffie-Hellman support classes
    KeyPairGenerator keyPairGenerator;
    KeyAgreement keyAgreement;
    KeyFactory keyFactory;
    try {
        keyPairGenerator = KeyPairGenerator.getInstance("DH");
        keyAgreement = KeyAgreement.getInstance("DH");
        keyFactory = KeyFactory.getInstance("DH");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        throw new IOException(MSG_NO_SUPPORT + " (Diffie-Hellman)");
    }
    try {
        // parse the peerKey
        DHPublicKeySpec peerKeySpec = new DHPublicKeySpec(peerKey, prime, generator);
        DHPublicKey peerPublicKey = (DHPublicKey) keyFactory.generatePublic(peerKeySpec);
        // generate my public/private key pair
        keyPairGenerator.initialize(new DHParameterSpec(prime, generator));
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        // perform key agreement
        keyAgreement.init(keyPair.getPrivate());
        keyAgreement.doPhase(peerPublicKey, true);
        // return the results
        DHResult result = new DHResult();
        result.publicKey = keyToBytes(keyPair.getPublic(), keyLength);
        result.privateKey = keyToBytes(keyPair.getPrivate(), keyLength);
        result.secretKey = keyAgreement.generateSecret();
        return result;
    } catch (GeneralSecurityException e) {
        e.printStackTrace();
        throw new IOException(MSG_ERROR + " (Key agreement)");
    }
}
Also used : KeyPair(java.security.KeyPair) DHPublicKey(javax.crypto.interfaces.DHPublicKey) GeneralSecurityException(java.security.GeneralSecurityException) DHParameterSpec(javax.crypto.spec.DHParameterSpec) KeyPairGenerator(java.security.KeyPairGenerator) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) DHPublicKeySpec(javax.crypto.spec.DHPublicKeySpec) KeyAgreement(javax.crypto.KeyAgreement) KeyFactory(java.security.KeyFactory)

Example 9 with DHPublicKeySpec

use of javax.crypto.spec.DHPublicKeySpec in project Zom-Android by zom.

the class OtrCryptoEngineImpl method generateDHKeyPair.

public KeyPair generateDHKeyPair() throws OtrCryptoException {
    // Generate a AsymmetricCipherKeyPair using BC.
    DHParameters dhParams = new DHParameters(MODULUS, GENERATOR, null, DH_PRIVATE_KEY_MINIMUM_BIT_LENGTH);
    DHKeyGenerationParameters params = new DHKeyGenerationParameters(new SecureRandom(), dhParams);
    DHKeyPairGenerator kpGen = new DHKeyPairGenerator();
    kpGen.init(params);
    AsymmetricCipherKeyPair pair = kpGen.generateKeyPair();
    // Convert this AsymmetricCipherKeyPair to a standard JCE KeyPair.
    DHPublicKeyParameters pub = (DHPublicKeyParameters) pair.getPublic();
    DHPrivateKeyParameters priv = (DHPrivateKeyParameters) pair.getPrivate();
    try {
        KeyFactory keyFac = KeyFactory.getInstance("DH");
        DHPublicKeySpec pubKeySpecs = new DHPublicKeySpec(pub.getY(), MODULUS, GENERATOR);
        DHPublicKey pubKey = (DHPublicKey) keyFac.generatePublic(pubKeySpecs);
        DHParameters dhParameters = priv.getParameters();
        DHPrivateKeySpec privKeySpecs = new DHPrivateKeySpec(priv.getX(), dhParameters.getP(), dhParameters.getG());
        DHPrivateKey privKey = (DHPrivateKey) keyFac.generatePrivate(privKeySpecs);
        return new KeyPair(pubKey, privKey);
    } catch (Exception e) {
        throw new OtrCryptoException(e);
    }
}
Also used : DHPrivateKey(javax.crypto.interfaces.DHPrivateKey) KeyPair(java.security.KeyPair) AsymmetricCipherKeyPair(org.spongycastle.crypto.AsymmetricCipherKeyPair) DHPublicKeyParameters(org.spongycastle.crypto.params.DHPublicKeyParameters) DHParameters(org.spongycastle.crypto.params.DHParameters) DHPublicKey(javax.crypto.interfaces.DHPublicKey) DHPrivateKeyParameters(org.spongycastle.crypto.params.DHPrivateKeyParameters) DHKeyGenerationParameters(org.spongycastle.crypto.params.DHKeyGenerationParameters) SecureRandom(java.security.SecureRandom) DHKeyPairGenerator(org.spongycastle.crypto.generators.DHKeyPairGenerator) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) AsymmetricCipherKeyPair(org.spongycastle.crypto.AsymmetricCipherKeyPair) DHPrivateKeySpec(javax.crypto.spec.DHPrivateKeySpec) DHPublicKeySpec(javax.crypto.spec.DHPublicKeySpec) KeyFactory(java.security.KeyFactory)

Example 10 with DHPublicKeySpec

use of javax.crypto.spec.DHPublicKeySpec in project j2objc by google.

the class DHPublicKeySpecTest method testDHPrivateKeySpec.

/**
 * DHPublicKeySpec class testing. Tests the equivalence of parameters
 * specified in the constructor with the values returned by getters.
 */
public void testDHPrivateKeySpec() {
    BigInteger[] ys = { new BigInteger("-1000000000000"), BigInteger.ZERO, BigInteger.ONE, new BigInteger("1000000000000") };
    BigInteger[] ps = { new BigInteger("-1000000000000"), BigInteger.ZERO, BigInteger.ONE, new BigInteger("1000000000000") };
    BigInteger[] gs = { new BigInteger("-1000000000000"), BigInteger.ZERO, BigInteger.ONE, new BigInteger("1000000000000") };
    for (int i = 0; i < ps.length; i++) {
        DHPublicKeySpec dhpks = new DHPublicKeySpec(ys[i], ps[i], gs[i]);
        assertEquals("The value returned by getY() must be " + "equal to the value specified in the constructor", dhpks.getY(), ys[i]);
        assertEquals("The value returned by getP() must be " + "equal to the value specified in the constructor", dhpks.getP(), ps[i]);
        assertEquals("The value returned by getG() must be " + "equal to the value specified in the constructor", dhpks.getG(), gs[i]);
    }
}
Also used : BigInteger(java.math.BigInteger) DHPublicKeySpec(javax.crypto.spec.DHPublicKeySpec)

Aggregations

DHPublicKeySpec (javax.crypto.spec.DHPublicKeySpec)17 KeyFactory (java.security.KeyFactory)13 DHPublicKey (javax.crypto.interfaces.DHPublicKey)12 BigInteger (java.math.BigInteger)11 PublicKey (java.security.PublicKey)11 IOException (java.io.IOException)9 DHParameterSpec (javax.crypto.spec.DHParameterSpec)9 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)8 KeyPair (java.security.KeyPair)6 KeyPairGenerator (java.security.KeyPairGenerator)6 CertificateException (java.security.cert.CertificateException)6 KeyAgreement (javax.crypto.KeyAgreement)6 Cipher (javax.crypto.Cipher)5 X509Certificate (java.security.cert.X509Certificate)4 RSAPublicKey (java.security.interfaces.RSAPublicKey)4 X509ExtendedKeyManager (javax.net.ssl.X509ExtendedKeyManager)4 X509KeyManager (javax.net.ssl.X509KeyManager)4 GeneralSecurityException (java.security.GeneralSecurityException)3 PrivateKey (java.security.PrivateKey)3 DHPrivateKeySpec (javax.crypto.spec.DHPrivateKeySpec)3