Search in sources :

Example 31 with KeyAgreement

use of javax.crypto.KeyAgreement in project jdk8u_jdk by JetBrains.

the class DHCrypt method getAgreedSecret.

/**
     * Get the secret data that has been agreed on through Diffie-Hellman
     * key agreement protocol.  Note that in the two party protocol, if
     * the peer keys are already known, no other data needs to be sent in
     * order to agree on a secret.  That is, a secured message may be
     * sent without any mandatory round-trip overheads.
     *
     * <P>It is illegal to call this member function if the private key
     * has not been set (or generated).
     *
     * @param  peerPublicKey the peer's public key.
     * @param  keyIsValidated whether the {@code peerPublicKey} has beed
     *         validated
     * @return the secret, which is an unsigned big-endian integer
     *         the same size as the Diffie-Hellman modulus.
     */
SecretKey getAgreedSecret(BigInteger peerPublicValue, boolean keyIsValidated) throws SSLHandshakeException {
    try {
        KeyFactory kf = JsseJce.getKeyFactory("DiffieHellman");
        DHPublicKeySpec spec = new DHPublicKeySpec(peerPublicValue, modulus, base);
        PublicKey publicKey = kf.generatePublic(spec);
        KeyAgreement ka = JsseJce.getKeyAgreement("DiffieHellman");
        // validate the Diffie-Hellman public key
        if (!keyIsValidated && !KeyUtil.isOracleJCEProvider(ka.getProvider().getName())) {
            try {
                KeyUtil.validate(spec);
            } catch (InvalidKeyException ike) {
                // prefer handshake_failure alert to internal_error alert
                throw new SSLHandshakeException(ike.getMessage());
            }
        }
        ka.init(privateKey);
        ka.doPhase(publicKey, true);
        return ka.generateSecret("TlsPremasterSecret");
    } catch (GeneralSecurityException e) {
        throw (SSLHandshakeException) new SSLHandshakeException("Could not generate secret").initCause(e);
    }
}
Also used : DHPublicKey(javax.crypto.interfaces.DHPublicKey) KeyAgreement(javax.crypto.KeyAgreement) SSLHandshakeException(javax.net.ssl.SSLHandshakeException)

Example 32 with KeyAgreement

use of javax.crypto.KeyAgreement in project geode by apache.

the class GMSEncrypt method getDecryptCipher.

// this needs to synchronize as it uses private key of that member
protected static synchronized Cipher getDecryptCipher(String dhSKAlgo, PrivateKey privateKey, PublicKey publicKey) throws Exception {
    KeyAgreement ka = KeyAgreement.getInstance("DH");
    ka.init(privateKey);
    ka.doPhase(publicKey, true);
    Cipher decrypt;
    int keysize = getKeySize(dhSKAlgo);
    int blocksize = getBlockSize(dhSKAlgo);
    if (keysize == -1 || blocksize == -1) {
        SecretKey sKey = ka.generateSecret(dhSKAlgo);
        decrypt = Cipher.getInstance(dhSKAlgo);
        decrypt.init(Cipher.DECRYPT_MODE, sKey);
    } else {
        String algoStr = getDhAlgoStr(dhSKAlgo);
        byte[] sKeyBytes = ka.generateSecret();
        SecretKeySpec sks = new SecretKeySpec(sKeyBytes, 0, keysize, algoStr);
        IvParameterSpec ivps = new IvParameterSpec(sKeyBytes, keysize, blocksize);
        decrypt = Cipher.getInstance(algoStr + "/CBC/PKCS5Padding");
        decrypt.init(Cipher.DECRYPT_MODE, sks, ivps);
    }
    return decrypt;
}
Also used : SecretKey(javax.crypto.SecretKey) SecretKeySpec(javax.crypto.spec.SecretKeySpec) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) KeyAgreement(javax.crypto.KeyAgreement)

Example 33 with KeyAgreement

use of javax.crypto.KeyAgreement in project geode by apache.

the class GMSEncrypt method generateSecret.

protected static byte[] generateSecret(String dhSKAlgo, PrivateKey privateKey, PublicKey otherPublicKey) throws Exception {
    KeyAgreement ka = KeyAgreement.getInstance("DH");
    ka.init(privateKey);
    ka.doPhase(otherPublicKey, true);
    int keysize = getKeySize(dhSKAlgo);
    int blocksize = getBlockSize(dhSKAlgo);
    if (keysize == -1 || blocksize == -1) {
        SecretKey sKey = ka.generateSecret(dhSKAlgo);
        return sKey.getEncoded();
    } else {
        return ka.generateSecret();
    }
}
Also used : SecretKey(javax.crypto.SecretKey) KeyAgreement(javax.crypto.KeyAgreement)

Example 34 with KeyAgreement

use of javax.crypto.KeyAgreement in project geode by apache.

the class GMSEncrypt method getEncryptCipher.

// this needs to synchronize as it uses private key of that member
protected static synchronized Cipher getEncryptCipher(String dhSKAlgo, PrivateKey privateKey, PublicKey peerPublicKey) throws Exception {
    KeyAgreement ka = KeyAgreement.getInstance("DH");
    ka.init(privateKey);
    ka.doPhase(peerPublicKey, true);
    Cipher encrypt;
    int keysize = getKeySize(dhSKAlgo);
    int blocksize = getBlockSize(dhSKAlgo);
    if (keysize == -1 || blocksize == -1) {
        SecretKey sKey = ka.generateSecret(dhSKAlgo);
        encrypt = Cipher.getInstance(dhSKAlgo);
        encrypt.init(Cipher.ENCRYPT_MODE, sKey);
    } else {
        String dhAlgoStr = getDhAlgoStr(dhSKAlgo);
        byte[] sKeyBytes = ka.generateSecret();
        SecretKeySpec sks = new SecretKeySpec(sKeyBytes, 0, keysize, dhAlgoStr);
        IvParameterSpec ivps = new IvParameterSpec(sKeyBytes, keysize, blocksize);
        encrypt = Cipher.getInstance(dhAlgoStr + "/CBC/PKCS5Padding");
        encrypt.init(Cipher.ENCRYPT_MODE, sks, ivps);
    }
    return encrypt;
}
Also used : SecretKey(javax.crypto.SecretKey) SecretKeySpec(javax.crypto.spec.SecretKeySpec) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) KeyAgreement(javax.crypto.KeyAgreement)

Example 35 with KeyAgreement

use of javax.crypto.KeyAgreement in project geode by apache.

the class HandShake method readCredentials.

// This assumes that authentication is the last piece of info in handshake
public static Properties readCredentials(DataInputStream dis, DataOutputStream dos, DistributedSystem system) throws GemFireSecurityException, IOException {
    boolean requireAuthentication = securityService.isClientSecurityRequired();
    Properties credentials = null;
    try {
        byte secureMode = dis.readByte();
        throwIfMissingRequiredCredentials(requireAuthentication, secureMode != CREDENTIALS_NONE);
        if (secureMode == CREDENTIALS_NORMAL) {
            if (requireAuthentication) {
                credentials = DataSerializer.readProperties(dis);
            } else {
                // ignore the credentials
                DataSerializer.readProperties(dis);
            }
        } else if (secureMode == CREDENTIALS_DHENCRYPT) {
            boolean sendAuthentication = dis.readBoolean();
            InternalLogWriter securityLogWriter = (InternalLogWriter) system.getSecurityLogWriter();
            // Get the symmetric encryption algorithm to be used
            String skAlgo = DataSerializer.readString(dis);
            // Get the public key of the other side
            byte[] keyBytes = DataSerializer.readByteArray(dis);
            byte[] challenge = null;
            PublicKey pubKey = null;
            if (requireAuthentication) {
                // Generate PublicKey from encoded form
                X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
                KeyFactory keyFact = KeyFactory.getInstance("DH");
                pubKey = keyFact.generatePublic(x509KeySpec);
                // Send the public key to other side
                keyBytes = dhPublicKey.getEncoded();
                challenge = new byte[64];
                random.nextBytes(challenge);
                // sign the challenge from client.
                if (sendAuthentication) {
                    // Get the challenge string from client
                    byte[] clientChallenge = DataSerializer.readByteArray(dis);
                    if (privateKeyEncrypt == null) {
                        throw new AuthenticationFailedException(LocalizedStrings.HandShake_SERVER_PRIVATE_KEY_NOT_AVAILABLE_FOR_CREATING_SIGNATURE.toLocalizedString());
                    }
                    // Sign the challenge from client and send it to the client
                    Signature sig = Signature.getInstance(privateKeySignAlgo);
                    sig.initSign(privateKeyEncrypt);
                    sig.update(clientChallenge);
                    byte[] signedBytes = sig.sign();
                    dos.writeByte(REPLY_OK);
                    DataSerializer.writeByteArray(keyBytes, dos);
                    // DataSerializer.writeString(privateKeyAlias, dos);
                    DataSerializer.writeString(privateKeySubject, dos);
                    DataSerializer.writeByteArray(signedBytes, dos);
                    securityLogWriter.fine("HandShake: sent the signed client challenge");
                } else {
                    // These two lines should not be moved before the if{} statement in
                    // a common block for both if...then...else parts. This is to handle
                    // the case when an AuthenticationFailedException is thrown by the
                    // if...then part when sending the signature.
                    dos.writeByte(REPLY_OK);
                    DataSerializer.writeByteArray(keyBytes, dos);
                }
                // Now send the server challenge
                DataSerializer.writeByteArray(challenge, dos);
                securityLogWriter.fine("HandShake: sent the public key and challenge");
                dos.flush();
                // Read and decrypt the credentials
                byte[] encBytes = DataSerializer.readByteArray(dis);
                KeyAgreement ka = KeyAgreement.getInstance("DH");
                ka.init(dhPrivateKey);
                ka.doPhase(pubKey, true);
                Cipher decrypt;
                int keysize = getKeySize(skAlgo);
                int blocksize = getBlockSize(skAlgo);
                if (keysize == -1 || blocksize == -1) {
                    SecretKey sKey = ka.generateSecret(skAlgo);
                    decrypt = Cipher.getInstance(skAlgo);
                    decrypt.init(Cipher.DECRYPT_MODE, sKey);
                } else {
                    String algoStr = getDhAlgoStr(skAlgo);
                    byte[] sKeyBytes = ka.generateSecret();
                    SecretKeySpec sks = new SecretKeySpec(sKeyBytes, 0, keysize, algoStr);
                    IvParameterSpec ivps = new IvParameterSpec(sKeyBytes, keysize, blocksize);
                    decrypt = Cipher.getInstance(algoStr + "/CBC/PKCS5Padding");
                    decrypt.init(Cipher.DECRYPT_MODE, sks, ivps);
                }
                byte[] credentialBytes = decrypt.doFinal(encBytes);
                ByteArrayInputStream bis = new ByteArrayInputStream(credentialBytes);
                DataInputStream dinp = new DataInputStream(bis);
                credentials = DataSerializer.readProperties(dinp);
                byte[] challengeRes = DataSerializer.readByteArray(dinp);
                // Check the challenge string
                if (!Arrays.equals(challenge, challengeRes)) {
                    throw new AuthenticationFailedException(LocalizedStrings.HandShake_MISMATCH_IN_CHALLENGE_BYTES_MALICIOUS_CLIENT.toLocalizedString());
                }
                dinp.close();
            } else {
                if (sendAuthentication) {
                    // Read and ignore the client challenge
                    DataSerializer.readByteArray(dis);
                }
                dos.writeByte(REPLY_AUTH_NOT_REQUIRED);
                dos.flush();
            }
        } else if (secureMode == SECURITY_MULTIUSER_NOTIFICATIONCHANNEL) {
            // hitesh there will be no credential CCP will get credential(Principal) using
            // ServerConnection..
            logger.debug("readCredential where multiuser mode creating callback connection");
        }
    } catch (IOException ex) {
        throw ex;
    } catch (GemFireSecurityException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new AuthenticationFailedException(LocalizedStrings.HandShake_FAILURE_IN_READING_CREDENTIALS.toLocalizedString(), ex);
    }
    return credentials;
}
Also used : InternalLogWriter(org.apache.geode.internal.logging.InternalLogWriter) AuthenticationFailedException(org.apache.geode.security.AuthenticationFailedException) PublicKey(java.security.PublicKey) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) IOException(java.io.IOException) Properties(java.util.Properties) VersionedDataInputStream(org.apache.geode.internal.VersionedDataInputStream) DataInputStream(java.io.DataInputStream) ServerRefusedConnectionException(org.apache.geode.cache.client.ServerRefusedConnectionException) GemFireSecurityException(org.apache.geode.security.GemFireSecurityException) InternalGemFireException(org.apache.geode.InternalGemFireException) GatewayConfigurationException(org.apache.geode.cache.GatewayConfigurationException) EOFException(java.io.EOFException) AuthenticationFailedException(org.apache.geode.security.AuthenticationFailedException) GemFireConfigException(org.apache.geode.GemFireConfigException) IOException(java.io.IOException) AuthenticationRequiredException(org.apache.geode.security.AuthenticationRequiredException) SecretKey(javax.crypto.SecretKey) GemFireSecurityException(org.apache.geode.security.GemFireSecurityException) ByteArrayInputStream(java.io.ByteArrayInputStream) SecretKeySpec(javax.crypto.spec.SecretKeySpec) Signature(java.security.Signature) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) KeyAgreement(javax.crypto.KeyAgreement) KeyFactory(java.security.KeyFactory)

Aggregations

KeyAgreement (javax.crypto.KeyAgreement)56 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