Java Code Examples for sun.security.util.KeyUtil#isOracleJCEProvider()

The following examples show how to use sun.security.util.KeyUtil#isOracleJCEProvider() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DHCrypt.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
private DHPublicKeySpec generateDHPublicKeySpec(KeyPairGenerator kpg)
        throws GeneralSecurityException {

    boolean doExtraValiadtion =
                (!KeyUtil.isOracleJCEProvider(kpg.getProvider().getName()));
    for (int i = 0; i <= MAX_FAILOVER_TIMES; i++) {
        KeyPair kp = kpg.generateKeyPair();
        privateKey = kp.getPrivate();
        DHPublicKeySpec spec = getDHPublicKeySpec(kp.getPublic());

        // validate the Diffie-Hellman public key
        if (doExtraValiadtion) {
            try {
                KeyUtil.validate(spec);
            } catch (InvalidKeyException ivke) {
                if (i == MAX_FAILOVER_TIMES) {
                    throw ivke;
                }
                // otherwise, ignore the exception and try the next one
                continue;
            }
        }

        return spec;
    }

    return null;
}
 
Example 2
Source File: DHCrypt.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 3
Source File: DHKeyExchange.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
private KeyPair generateDHKeyPair(
        KeyPairGenerator kpg) throws GeneralSecurityException {
    boolean doExtraValidation =
            (!KeyUtil.isOracleJCEProvider(kpg.getProvider().getName()));
    boolean isRecovering = false;
    for (int i = 0; i <= 2; i++) {      // Try to recover from failure.
        KeyPair kp = kpg.generateKeyPair();
        // validate the Diffie-Hellman public key
        if (doExtraValidation) {
            DHPublicKeySpec spec = getDHPublicKeySpec(kp.getPublic());
            try {
                KeyUtil.validate(spec);
            } catch (InvalidKeyException ivke) {
                if (isRecovering) {
                    throw ivke;
                }
                // otherwise, ignore the exception and try again
                isRecovering = true;
                continue;
            }
        }

        return kp;
    }

    return null;
}
 
Example 4
Source File: DHCrypt.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private DHPublicKeySpec generateDHPublicKeySpec(KeyPairGenerator kpg)
        throws GeneralSecurityException {

    boolean doExtraValiadtion =
                (!KeyUtil.isOracleJCEProvider(kpg.getProvider().getName()));
    for (int i = 0; i <= MAX_FAILOVER_TIMES; i++) {
        KeyPair kp = kpg.generateKeyPair();
        privateKey = kp.getPrivate();
        DHPublicKeySpec spec = getDHPublicKeySpec(kp.getPublic());

        // validate the Diffie-Hellman public key
        if (doExtraValiadtion) {
            try {
                KeyUtil.validate(spec);
            } catch (InvalidKeyException ivke) {
                if (i == MAX_FAILOVER_TIMES) {
                    throw ivke;
                }
                // otherwise, ignore the exception and try the next one
                continue;
            }
        }

        return spec;
    }

    return null;
}
 
Example 5
Source File: DHCrypt.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 6
Source File: DHCrypt.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
private DHPublicKeySpec generateDHPublicKeySpec(KeyPairGenerator kpg)
        throws GeneralSecurityException {

    boolean doExtraValiadtion =
                (!KeyUtil.isOracleJCEProvider(kpg.getProvider().getName()));
    for (int i = 0; i <= MAX_FAILOVER_TIMES; i++) {
        KeyPair kp = kpg.generateKeyPair();
        privateKey = kp.getPrivate();
        DHPublicKeySpec spec = getDHPublicKeySpec(kp.getPublic());

        // validate the Diffie-Hellman public key
        if (doExtraValiadtion) {
            try {
                KeyUtil.validate(spec);
            } catch (InvalidKeyException ivke) {
                if (i == MAX_FAILOVER_TIMES) {
                    throw ivke;
                }
                // otherwise, ignore the exception and try the next one
                continue;
            }
        }

        return spec;
    }

    return null;
}
 
Example 7
Source File: DHCrypt.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private DHPublicKeySpec generateDHPublicKeySpec(KeyPairGenerator kpg)
        throws GeneralSecurityException {

    boolean doExtraValiadtion =
                (!KeyUtil.isOracleJCEProvider(kpg.getProvider().getName()));
    for (int i = 0; i <= MAX_FAILOVER_TIMES; i++) {
        KeyPair kp = kpg.generateKeyPair();
        privateKey = kp.getPrivate();
        DHPublicKeySpec spec = getDHPublicKeySpec(kp.getPublic());

        // validate the Diffie-Hellman public key
        if (doExtraValiadtion) {
            try {
                KeyUtil.validate(spec);
            } catch (InvalidKeyException ivke) {
                if (i == MAX_FAILOVER_TIMES) {
                    throw ivke;
                }
                // otherwise, ignore the exception and try the next one
                continue;
            }
        }

        return spec;
    }

    return null;
}
 
Example 8
Source File: DHCrypt.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 IOException {
    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 new RuntimeException("Could not generate secret", e);
    }
}
 
Example 9
Source File: DHCrypt.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
private DHPublicKeySpec generateDHPublicKeySpec(KeyPairGenerator kpg)
        throws GeneralSecurityException {

    boolean doExtraValiadtion =
                (!KeyUtil.isOracleJCEProvider(kpg.getProvider().getName()));
    for (int i = 0; i <= MAX_FAILOVER_TIMES; i++) {
        KeyPair kp = kpg.generateKeyPair();
        privateKey = kp.getPrivate();
        DHPublicKeySpec spec = getDHPublicKeySpec(kp.getPublic());

        // validate the Diffie-Hellman public key
        if (doExtraValiadtion) {
            try {
                KeyUtil.validate(spec);
            } catch (InvalidKeyException ivke) {
                if (i == MAX_FAILOVER_TIMES) {
                    throw ivke;
                }
                // otherwise, ignore the exception and try the next one
                continue;
            }
        }

        return spec;
    }

    return null;
}
 
Example 10
Source File: DHCrypt.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private DHPublicKeySpec generateDHPublicKeySpec(KeyPairGenerator kpg)
        throws GeneralSecurityException {

    boolean doExtraValiadtion =
                (!KeyUtil.isOracleJCEProvider(kpg.getProvider().getName()));
    for (int i = 0; i <= MAX_FAILOVER_TIMES; i++) {
        KeyPair kp = kpg.generateKeyPair();
        privateKey = kp.getPrivate();
        DHPublicKeySpec spec = getDHPublicKeySpec(kp.getPublic());

        // validate the Diffie-Hellman public key
        if (doExtraValiadtion) {
            try {
                KeyUtil.validate(spec);
            } catch (InvalidKeyException ivke) {
                if (i == MAX_FAILOVER_TIMES) {
                    throw ivke;
                }
                // otherwise, ignore the exception and try the next one
                continue;
            }
        }

        return spec;
    }

    return null;
}
 
Example 11
Source File: DHCrypt.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 IOException {
    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 new RuntimeException("Could not generate secret", e);
    }
}
 
Example 12
Source File: DHCrypt.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 13
Source File: DHCrypt.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private DHPublicKeySpec generateDHPublicKeySpec(KeyPairGenerator kpg)
        throws GeneralSecurityException {

    boolean doExtraValiadtion =
                (!KeyUtil.isOracleJCEProvider(kpg.getProvider().getName()));
    for (int i = 0; i <= MAX_FAILOVER_TIMES; i++) {
        KeyPair kp = kpg.generateKeyPair();
        privateKey = kp.getPrivate();
        DHPublicKeySpec spec = getDHPublicKeySpec(kp.getPublic());

        // validate the Diffie-Hellman public key
        if (doExtraValiadtion) {
            try {
                KeyUtil.validate(spec);
            } catch (InvalidKeyException ivke) {
                if (i == MAX_FAILOVER_TIMES) {
                    throw ivke;
                }
                // otherwise, ignore the exception and try the next one
                continue;
            }
        }

        return spec;
    }

    return null;
}
 
Example 14
Source File: DHCrypt.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private DHPublicKeySpec generateDHPublicKeySpec(KeyPairGenerator kpg)
        throws GeneralSecurityException {

    boolean doExtraValiadtion =
                (!KeyUtil.isOracleJCEProvider(kpg.getProvider().getName()));
    for (int i = 0; i <= MAX_FAILOVER_TIMES; i++) {
        KeyPair kp = kpg.generateKeyPair();
        privateKey = kp.getPrivate();
        DHPublicKeySpec spec = getDHPublicKeySpec(kp.getPublic());

        // validate the Diffie-Hellman public key
        if (doExtraValiadtion) {
            try {
                KeyUtil.validate(spec);
            } catch (InvalidKeyException ivke) {
                if (i == MAX_FAILOVER_TIMES) {
                    throw ivke;
                }
                // otherwise, ignore the exception and try the next one
                continue;
            }
        }

        return spec;
    }

    return null;
}
 
Example 15
Source File: DHCrypt.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 16
Source File: RSAClientKeyExchange.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
RSAClientKeyExchange(ProtocolVersion currentVersion,
        ProtocolVersion maxVersion,
        SecureRandom generator, HandshakeInStream input,
        int messageSize, PrivateKey privateKey) throws IOException {

    if (privateKey.getAlgorithm().equals("RSA") == false) {
        throw new SSLKeyException("Private key not of type RSA: " +
             privateKey.getAlgorithm());
    }

    if (currentVersion.v >= ProtocolVersion.TLS10.v) {
        encrypted = input.getBytes16();
    } else {
        encrypted = new byte [messageSize];
        if (input.read(encrypted) != messageSize) {
            throw new SSLProtocolException(
                    "SSL: read PreMasterSecret: short read");
        }
    }

    byte[] encoded = null;
    try {
        boolean needFailover = false;
        Cipher cipher = JsseJce.getCipher(JsseJce.CIPHER_RSA_PKCS1);
        try {
            // Try UNWRAP_MODE mode firstly.
            cipher.init(Cipher.UNWRAP_MODE, privateKey,
                    new TlsRsaPremasterSecretParameterSpec(
                            maxVersion.v, currentVersion.v),
                    generator);

            // The provider selection can be delayed, please don't call
            // any Cipher method before the call to Cipher.init().
            needFailover = !KeyUtil.isOracleJCEProvider(
                    cipher.getProvider().getName());
        } catch (InvalidKeyException | UnsupportedOperationException iue) {
            if (debug != null && Debug.isOn("handshake")) {
                System.out.println("The Cipher provider "
                        + safeProviderName(cipher)
                        + " caused exception: " + iue.getMessage());
            }

            needFailover = true;
        }

        if (needFailover) {
            // The cipher might be spoiled by unsuccessful call to init(),
            // so request a fresh instance
            cipher = JsseJce.getCipher(JsseJce.CIPHER_RSA_PKCS1);

            // Use DECRYPT_MODE and dispose the previous initialization.
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            boolean failed = false;
            try {
                encoded = cipher.doFinal(encrypted);
            } catch (BadPaddingException bpe) {
                // Note: encoded == null
                failed = true;
            }
            encoded = KeyUtil.checkTlsPreMasterSecretKey(
                            maxVersion.v, currentVersion.v,
                            generator, encoded, failed);
            preMaster = generatePreMasterSecret(
                            maxVersion.v, currentVersion.v,
                            encoded, generator);
        } else {
            // the cipher should have been initialized
            preMaster = (SecretKey)cipher.unwrap(encrypted,
                    "TlsRsaPremasterSecret", Cipher.SECRET_KEY);
        }
    } catch (InvalidKeyException ibk) {
        // the message is too big to process with RSA
        throw new SSLException(
            "Unable to process PreMasterSecret", ibk);
    } catch (Exception e) {
        // unlikely to happen, otherwise, must be a provider exception
        if (debug != null && Debug.isOn("handshake")) {
            System.out.println("RSA premaster secret decryption error:");
            e.printStackTrace(System.out);
        }
        throw new RuntimeException("Could not generate dummy secret", e);
    }
}
 
Example 17
Source File: RSAClientKeyExchange.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
RSAClientKeyExchange(ProtocolVersion currentVersion,
        ProtocolVersion maxVersion,
        SecureRandom generator, HandshakeInStream input,
        int messageSize, PrivateKey privateKey) throws IOException {

    if (privateKey.getAlgorithm().equals("RSA") == false) {
        throw new SSLKeyException("Private key not of type RSA: " +
             privateKey.getAlgorithm());
    }

    if (currentVersion.v >= ProtocolVersion.TLS10.v) {
        encrypted = input.getBytes16();
    } else {
        encrypted = new byte [messageSize];
        if (input.read(encrypted) != messageSize) {
            throw new SSLProtocolException(
                    "SSL: read PreMasterSecret: short read");
        }
    }

    byte[] encoded = null;
    try {
        boolean needFailover = false;
        Cipher cipher = JsseJce.getCipher(JsseJce.CIPHER_RSA_PKCS1);
        try {
            // Try UNWRAP_MODE mode firstly.
            cipher.init(Cipher.UNWRAP_MODE, privateKey,
                    new TlsRsaPremasterSecretParameterSpec(
                            maxVersion.v, currentVersion.v),
                    generator);

            // The provider selection can be delayed, please don't call
            // any Cipher method before the call to Cipher.init().
            needFailover = !KeyUtil.isOracleJCEProvider(
                    cipher.getProvider().getName());
        } catch (InvalidKeyException | UnsupportedOperationException iue) {
            if (debug != null && Debug.isOn("handshake")) {
                System.out.println("The Cipher provider " +
                    cipher.getProvider().getName() +
                    " caused exception: " + iue.getMessage());
            }

            needFailover = true;
        }

        if (needFailover) {
            // Use DECRYPT_MODE and dispose the previous initialization.
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            boolean failed = false;
            try {
                encoded = cipher.doFinal(encrypted);
            } catch (BadPaddingException bpe) {
                // Note: encoded == null
                failed = true;
            }
            encoded = KeyUtil.checkTlsPreMasterSecretKey(
                            maxVersion.v, currentVersion.v,
                            generator, encoded, failed);
            preMaster = generatePreMasterSecret(
                            maxVersion.v, currentVersion.v,
                            encoded, generator);
        } else {
            // the cipher should have been initialized
            preMaster = (SecretKey)cipher.unwrap(encrypted,
                    "TlsRsaPremasterSecret", Cipher.SECRET_KEY);
        }
    } catch (InvalidKeyException ibk) {
        // the message is too big to process with RSA
        throw new SSLException(
            "Unable to process PreMasterSecret", ibk);
    } catch (Exception e) {
        // unlikely to happen, otherwise, must be a provider exception
        if (debug != null && Debug.isOn("handshake")) {
            System.out.println("RSA premaster secret decryption error:");
            e.printStackTrace(System.out);
        }
        throw new RuntimeException("Could not generate dummy secret", e);
    }
}
 
Example 18
Source File: RSAClientKeyExchange.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
RSAClientKeyExchange(ProtocolVersion currentVersion,
        ProtocolVersion maxVersion,
        SecureRandom generator, HandshakeInStream input,
        int messageSize, PrivateKey privateKey) throws IOException {

    if (privateKey.getAlgorithm().equals("RSA") == false) {
        throw new SSLKeyException("Private key not of type RSA: " +
             privateKey.getAlgorithm());
    }

    if (currentVersion.v >= ProtocolVersion.TLS10.v) {
        encrypted = input.getBytes16();
    } else {
        encrypted = new byte [messageSize];
        if (input.read(encrypted) != messageSize) {
            throw new SSLProtocolException(
                    "SSL: read PreMasterSecret: short read");
        }
    }

    byte[] encoded = null;
    try {
        boolean needFailover = false;
        Cipher cipher = JsseJce.getCipher(JsseJce.CIPHER_RSA_PKCS1);
        try {
            // Try UNWRAP_MODE mode firstly.
            cipher.init(Cipher.UNWRAP_MODE, privateKey,
                    new TlsRsaPremasterSecretParameterSpec(
                            maxVersion.v, currentVersion.v),
                    generator);

            // The provider selection can be delayed, please don't call
            // any Cipher method before the call to Cipher.init().
            needFailover = !KeyUtil.isOracleJCEProvider(
                    cipher.getProvider().getName());
        } catch (InvalidKeyException | UnsupportedOperationException iue) {
            if (debug != null && Debug.isOn("handshake")) {
                System.out.println("The Cipher provider "
                        + safeProviderName(cipher)
                        + " caused exception: " + iue.getMessage());
            }

            needFailover = true;
        }

        if (needFailover) {
            // The cipher might be spoiled by unsuccessful call to init(),
            // so request a fresh instance
            cipher = JsseJce.getCipher(JsseJce.CIPHER_RSA_PKCS1);

            // Use DECRYPT_MODE and dispose the previous initialization.
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            boolean failed = false;
            try {
                encoded = cipher.doFinal(encrypted);
            } catch (BadPaddingException bpe) {
                // Note: encoded == null
                failed = true;
            }
            encoded = KeyUtil.checkTlsPreMasterSecretKey(
                            maxVersion.v, currentVersion.v,
                            generator, encoded, failed);
            preMaster = generatePreMasterSecret(
                            maxVersion.v, currentVersion.v,
                            encoded, generator);
        } else {
            // the cipher should have been initialized
            preMaster = (SecretKey)cipher.unwrap(encrypted,
                    "TlsRsaPremasterSecret", Cipher.SECRET_KEY);
        }
    } catch (InvalidKeyException ibk) {
        // the message is too big to process with RSA
        throw new SSLException(
            "Unable to process PreMasterSecret", ibk);
    } catch (Exception e) {
        // unlikely to happen, otherwise, must be a provider exception
        if (debug != null && Debug.isOn("handshake")) {
            System.out.println("RSA premaster secret decryption error:");
            e.printStackTrace(System.out);
        }
        throw new RuntimeException("Could not generate dummy secret", e);
    }
}
 
Example 19
Source File: RSAClientKeyExchange.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
RSAClientKeyExchange(ProtocolVersion currentVersion,
        ProtocolVersion maxVersion,
        SecureRandom generator, HandshakeInStream input,
        int messageSize, PrivateKey privateKey) throws IOException {

    if (privateKey.getAlgorithm().equals("RSA") == false) {
        throw new SSLKeyException("Private key not of type RSA: " +
             privateKey.getAlgorithm());
    }

    if (currentVersion.v >= ProtocolVersion.TLS10.v) {
        encrypted = input.getBytes16();
    } else {
        encrypted = new byte [messageSize];
        if (input.read(encrypted) != messageSize) {
            throw new SSLProtocolException(
                    "SSL: read PreMasterSecret: short read");
        }
    }

    byte[] encoded = null;
    try {
        boolean needFailover = false;
        Cipher cipher = JsseJce.getCipher(JsseJce.CIPHER_RSA_PKCS1);
        try {
            // Try UNWRAP_MODE mode firstly.
            cipher.init(Cipher.UNWRAP_MODE, privateKey,
                    new TlsRsaPremasterSecretParameterSpec(
                            maxVersion.v, currentVersion.v),
                    generator);

            // The provider selection can be delayed, please don't call
            // any Cipher method before the call to Cipher.init().
            needFailover = !KeyUtil.isOracleJCEProvider(
                    cipher.getProvider().getName());
        } catch (InvalidKeyException | UnsupportedOperationException iue) {
            if (debug != null && Debug.isOn("handshake")) {
                System.out.println("The Cipher provider "
                        + safeProviderName(cipher)
                        + " caused exception: " + iue.getMessage());
            }

            needFailover = true;
        }

        if (needFailover) {
            // The cipher might be spoiled by unsuccessful call to init(),
            // so request a fresh instance
            cipher = JsseJce.getCipher(JsseJce.CIPHER_RSA_PKCS1);

            // Use DECRYPT_MODE and dispose the previous initialization.
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            boolean failed = false;
            try {
                encoded = cipher.doFinal(encrypted);
            } catch (BadPaddingException bpe) {
                // Note: encoded == null
                failed = true;
            }
            encoded = KeyUtil.checkTlsPreMasterSecretKey(
                            maxVersion.v, currentVersion.v,
                            generator, encoded, failed);
            preMaster = generatePreMasterSecret(
                            maxVersion.v, currentVersion.v,
                            encoded, generator);
        } else {
            // the cipher should have been initialized
            preMaster = (SecretKey)cipher.unwrap(encrypted,
                    "TlsRsaPremasterSecret", Cipher.SECRET_KEY);
        }
    } catch (InvalidKeyException ibk) {
        // the message is too big to process with RSA
        throw new SSLException(
            "Unable to process PreMasterSecret", ibk);
    } catch (Exception e) {
        // unlikely to happen, otherwise, must be a provider exception
        if (debug != null && Debug.isOn("handshake")) {
            System.out.println("RSA premaster secret decryption error:");
            e.printStackTrace(System.out);
        }
        throw new RuntimeException("Could not generate dummy secret", e);
    }
}
 
Example 20
Source File: RSAClientKeyExchange.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
RSAClientKeyExchange(ProtocolVersion currentVersion,
        ProtocolVersion maxVersion,
        SecureRandom generator, HandshakeInStream input,
        int messageSize, PrivateKey privateKey) throws IOException {

    if (privateKey.getAlgorithm().equals("RSA") == false) {
        throw new SSLKeyException("Private key not of type RSA: " +
             privateKey.getAlgorithm());
    }

    if (currentVersion.v >= ProtocolVersion.TLS10.v) {
        encrypted = input.getBytes16();
    } else {
        encrypted = new byte [messageSize];
        if (input.read(encrypted) != messageSize) {
            throw new SSLProtocolException(
                    "SSL: read PreMasterSecret: short read");
        }
    }

    byte[] encoded = null;
    try {
        boolean needFailover = false;
        Cipher cipher = JsseJce.getCipher(JsseJce.CIPHER_RSA_PKCS1);
        try {
            // Try UNWRAP_MODE mode firstly.
            cipher.init(Cipher.UNWRAP_MODE, privateKey,
                    new TlsRsaPremasterSecretParameterSpec(
                            maxVersion.v, currentVersion.v),
                    generator);

            // The provider selection can be delayed, please don't call
            // any Cipher method before the call to Cipher.init().
            needFailover = !KeyUtil.isOracleJCEProvider(
                    cipher.getProvider().getName());
        } catch (InvalidKeyException | UnsupportedOperationException iue) {
            if (debug != null && Debug.isOn("handshake")) {
                System.out.println("The Cipher provider "
                        + safeProviderName(cipher)
                        + " caused exception: " + iue.getMessage());
            }

            needFailover = true;
        }

        if (needFailover) {
            // The cipher might be spoiled by unsuccessful call to init(),
            // so request a fresh instance
            cipher = JsseJce.getCipher(JsseJce.CIPHER_RSA_PKCS1);

            // Use DECRYPT_MODE and dispose the previous initialization.
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            boolean failed = false;
            try {
                encoded = cipher.doFinal(encrypted);
            } catch (BadPaddingException bpe) {
                // Note: encoded == null
                failed = true;
            }
            encoded = KeyUtil.checkTlsPreMasterSecretKey(
                            maxVersion.v, currentVersion.v,
                            generator, encoded, failed);
            preMaster = generatePreMasterSecret(
                            maxVersion.v, currentVersion.v,
                            encoded, generator);
        } else {
            // the cipher should have been initialized
            preMaster = (SecretKey)cipher.unwrap(encrypted,
                    "TlsRsaPremasterSecret", Cipher.SECRET_KEY);
        }
    } catch (InvalidKeyException ibk) {
        // the message is too big to process with RSA
        throw new SSLException(
            "Unable to process PreMasterSecret", ibk);
    } catch (Exception e) {
        // unlikely to happen, otherwise, must be a provider exception
        if (debug != null && Debug.isOn("handshake")) {
            System.out.println("RSA premaster secret decryption error:");
            e.printStackTrace(System.out);
        }
        throw new RuntimeException("Could not generate dummy secret", e);
    }
}