javax.net.ssl.SSLHandshakeException Java Examples

The following examples show how to use javax.net.ssl.SSLHandshakeException. 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: JConsole.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
private String errorMessage(Exception ex) {
   String msg = Messages.CONNECTION_FAILED;
   if (ex instanceof IOException || ex instanceof SecurityException) {
       Throwable cause = null;
       Throwable c = ex.getCause();
       while (c != null) {
           cause = c;
           c = c.getCause();
       }
       if (cause instanceof ConnectException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof UnknownHostException) {
           return Resources.format(Messages.UNKNOWN_HOST, cause.getMessage());
       } else if (cause instanceof NoRouteToHostException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof FailedLoginException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof SSLHandshakeException) {
           return msg + ": "+ cause.getMessage();
       }
    } else if (ex instanceof MalformedURLException) {
       return Resources.format(Messages.INVALID_URL, ex.getMessage());
    }
    return msg + ": " + ex.getMessage();
}
 
Example #2
Source File: ECDHCrypt.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
SecretKey getAgreedSecret(
        byte[] encodedPoint) throws SSLHandshakeException {

    try {
        ECParameterSpec params = publicKey.getParams();
        ECPoint point =
                JsseJce.decodePoint(encodedPoint, params.getCurve());
        KeyFactory kf = JsseJce.getKeyFactory("EC");
        ECPublicKeySpec spec = new ECPublicKeySpec(point, params);
        PublicKey peerPublicKey = kf.generatePublic(spec);
        return getAgreedSecret(peerPublicKey);
    } catch (GeneralSecurityException | java.io.IOException e) {
        throw (SSLHandshakeException) new SSLHandshakeException(
            "Could not generate secret").initCause(e);
    }
}
 
Example #3
Source File: JConsole.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private String errorMessage(Exception ex) {
   String msg = Messages.CONNECTION_FAILED;
   if (ex instanceof IOException || ex instanceof SecurityException) {
       Throwable cause = null;
       Throwable c = ex.getCause();
       while (c != null) {
           cause = c;
           c = c.getCause();
       }
       if (cause instanceof ConnectException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof UnknownHostException) {
           return Resources.format(Messages.UNKNOWN_HOST, cause.getMessage());
       } else if (cause instanceof NoRouteToHostException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof FailedLoginException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof SSLHandshakeException) {
           return msg + ": "+ cause.getMessage();
       }
    } else if (ex instanceof MalformedURLException) {
       return Resources.format(Messages.INVALID_URL, ex.getMessage());
    }
    return msg + ": " + ex.getMessage();
}
 
Example #4
Source File: SSLTrafficKeyDerivation.java    From openjsse with GNU General Public License v2.0 6 votes vote down vote up
@Override
public SecretKey deriveKey(String algorithm,
        AlgorithmParameterSpec params) throws IOException {
    KeySchedule ks = KeySchedule.valueOf(algorithm);
    try {
        HKDF hkdf = new HKDF(cs.hashAlg.name);
        byte[] hkdfInfo =
                createHkdfInfo(ks.label, ks.getKeyLength(cs));
        return hkdf.expand(secret, hkdfInfo,
                ks.getKeyLength(cs),
                ks.getAlgorithm(cs, algorithm));
    } catch (GeneralSecurityException gse) {
        throw (SSLHandshakeException)(new SSLHandshakeException(
            "Could not generate secret").initCause(gse));
    }
}
 
Example #5
Source File: JMXStartStopTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private static void testNoConnect(int port, int rmiPort) throws Exception {
    try {
        testConnect(port, rmiPort);
        throw new Exception("Didn't expect the management agent running");
    } catch (Exception e) {
        Throwable t = e;
        while (t != null) {
            if (t instanceof NoSuchObjectException ||
                t instanceof ConnectException ||
                t instanceof SSLHandshakeException) {
                break;
            }
            t = t.getCause();
        }
        if (t == null) {
            throw new Exception("Unexpected exception", e);
        }
    }
}
 
Example #6
Source File: DHCrypt.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
void checkConstraints(AlgorithmConstraints constraints,
        BigInteger peerPublicValue) throws SSLHandshakeException {

    try {
        KeyFactory kf = JsseJce.getKeyFactory("DiffieHellman");
        DHPublicKeySpec spec =
                    new DHPublicKeySpec(peerPublicValue, modulus, base);
        DHPublicKey publicKey = (DHPublicKey)kf.generatePublic(spec);

        // check constraints of DHPublicKey
        if (!constraints.permits(
                EnumSet.of(CryptoPrimitive.KEY_AGREEMENT), publicKey)) {
            throw new SSLHandshakeException(
                "DHPublicKey does not comply to algorithm constraints");
        }
    } catch (GeneralSecurityException gse) {
        throw (SSLHandshakeException) new SSLHandshakeException(
                "Could not generate DHPublicKey").initCause(gse);
    }
}
 
Example #7
Source File: NetworkIOException.java    From dropbox-sdk-java with MIT License 6 votes vote down vote up
private static String computeMessage(IOException ex) {
    String message = ex.getMessage();

    // For CertPathValidationErrors, the CertPath is in the exception object but not
    // in the exception message.  Pull it out into the message, because it would be
    // useful for debugging.
    if (ex instanceof SSLHandshakeException) {
        Throwable innerCause = ex.getCause();
        if (innerCause instanceof CertPathValidatorException) {
            CertPathValidatorException cpve = (CertPathValidatorException) innerCause;
            message += "[CERT PATH: " + cpve.getCertPath() + "]";
        }
    }

    return message;
}
 
Example #8
Source File: JMXStartStopTest.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
private static void testNoConnect(int port, int rmiPort) throws Exception {
    try {
        testConnect(port, rmiPort);
        throw new Exception("Didn't expect the management agent running");
    } catch (Exception e) {
        Throwable t = e;
        while (t != null) {
            if (t instanceof NoSuchObjectException ||
                t instanceof ConnectException ||
                t instanceof SSLHandshakeException) {
                break;
            }
            t = t.getCause();
        }
        if (t == null) {
            throw new Exception("Unexpected exception", e);
        }
    }
}
 
Example #9
Source File: ECDHKeyExchange.java    From openjsse with GNU General Public License v2.0 6 votes vote down vote up
void checkConstraints(AlgorithmConstraints constraints,
        byte[] encodedPoint) throws SSLHandshakeException {
    try {

        ECParameterSpec params = publicKey.getParams();
        ECPoint point =
                JsseJce.decodePoint(encodedPoint, params.getCurve());
        ECPublicKeySpec spec = new ECPublicKeySpec(point, params);

        KeyFactory kf = JsseJce.getKeyFactory("EC");
        ECPublicKey pubKey = (ECPublicKey)kf.generatePublic(spec);

        // check constraints of ECPublicKey
        if (!constraints.permits(
                EnumSet.of(CryptoPrimitive.KEY_AGREEMENT), pubKey)) {
            throw new SSLHandshakeException(
                "ECPublicKey does not comply to algorithm constraints");
        }
    } catch (GeneralSecurityException | java.io.IOException e) {
        throw (SSLHandshakeException) new SSLHandshakeException(
                "Could not generate ECPublicKey").initCause(e);
    }
}
 
Example #10
Source File: Datastore.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Determine whether the given status maps to the error that GRPC-Java throws when an Android
 * device is missing required SSL Ciphers.
 *
 * <p>This error is non-recoverable and must be addressed by the app developer.
 */
public static boolean isMissingSslCiphers(Status status) {
  Status.Code code = status.getCode();
  Throwable t = status.getCause();

  // Check for the presence of a cipher error in the event of an SSLHandshakeException. This is
  // the special case of SSLHandshakeException that contains the cipher error.
  boolean hasCipherError = false;
  if (t instanceof SSLHandshakeException && t.getMessage().contains("no ciphers available")) {
    hasCipherError = true;
  }

  return Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP
      && code.equals(Status.Code.UNAVAILABLE)
      && hasCipherError;
}
 
Example #11
Source File: ReferenceCountedOpenSslClientContext.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
public KeyMaterial requested(long ssl, byte[] keyTypeBytes, byte[][] asn1DerEncodedPrincipals) {
    final ReferenceCountedOpenSslEngine engine = engineMap.get(ssl);
    try {
        final Set<String> keyTypesSet = supportedClientKeyTypes(keyTypeBytes);
        final String[] keyTypes = keyTypesSet.toArray(new String[keyTypesSet.size()]);
        final X500Principal[] issuers;
        if (asn1DerEncodedPrincipals == null) {
            issuers = null;
        } else {
            issuers = new X500Principal[asn1DerEncodedPrincipals.length];
            for (int i = 0; i < asn1DerEncodedPrincipals.length; i++) {
                issuers[i] = new X500Principal(asn1DerEncodedPrincipals[i]);
            }
        }
        return keyManagerHolder.keyMaterial(engine, keyTypes, issuers);
    } catch (Throwable cause) {
        logger.debug("request of key failed", cause);
        SSLHandshakeException e = new SSLHandshakeException("General OpenSslEngine problem");
        e.initCause(cause);
        engine.handshakeException = e;
        return null;
    }
}
 
Example #12
Source File: ECDHCrypt.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
SecretKey getAgreedSecret(
        byte[] encodedPoint) throws SSLHandshakeException {

    try {
        ECParameterSpec params = publicKey.getParams();
        ECPoint point =
                JsseJce.decodePoint(encodedPoint, params.getCurve());
        KeyFactory kf = JsseJce.getKeyFactory("EC");
        ECPublicKeySpec spec = new ECPublicKeySpec(point, params);
        PublicKey peerPublicKey = kf.generatePublic(spec);
        return getAgreedSecret(peerPublicKey);
    } catch (GeneralSecurityException | java.io.IOException e) {
        throw (SSLHandshakeException) new SSLHandshakeException(
            "Could not generate secret").initCause(e);
    }
}
 
Example #13
Source File: DHCrypt.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
void checkConstraints(AlgorithmConstraints constraints,
        BigInteger peerPublicValue) throws SSLHandshakeException {

    try {
        KeyFactory kf = JsseJce.getKeyFactory("DiffieHellman");
        DHPublicKeySpec spec =
                    new DHPublicKeySpec(peerPublicValue, modulus, base);
        DHPublicKey publicKey = (DHPublicKey)kf.generatePublic(spec);

        // check constraints of DHPublicKey
        if (!constraints.permits(
                EnumSet.of(CryptoPrimitive.KEY_AGREEMENT), publicKey)) {
            throw new SSLHandshakeException(
                "DHPublicKey does not comply to algorithm constraints");
        }
    } catch (GeneralSecurityException gse) {
        throw (SSLHandshakeException) new SSLHandshakeException(
                "Could not generate DHPublicKey").initCause(gse);
    }
}
 
Example #14
Source File: CertificateStatus.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
@Override
public void send(HandshakeOutStream s) throws IOException {
    s.putInt8(statusType.id);
    if (statusType == CertStatusRequestType.OCSP) {
        s.putBytes24(encodedResponses.get(0));
    } else if (statusType == CertStatusRequestType.OCSP_MULTI) {
        s.putInt24(encodedResponsesLen);
        for (byte[] respBytes : encodedResponses) {
            if (respBytes != null) {
                s.putBytes24(respBytes);
            } else {
                s.putBytes24(null);
            }
        }
    } else {
        // It is highly unlikely that we will fall into this section
        // of the code.
        throw new SSLHandshakeException("Unsupported status_type: " +
                statusType.id);
    }
}
 
Example #15
Source File: DHCrypt.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
void checkConstraints(AlgorithmConstraints constraints,
        BigInteger peerPublicValue) throws SSLHandshakeException {

    try {
        KeyFactory kf = JsseJce.getKeyFactory("DiffieHellman");
        DHPublicKeySpec spec =
                    new DHPublicKeySpec(peerPublicValue, modulus, base);
        DHPublicKey publicKey = (DHPublicKey)kf.generatePublic(spec);

        // check constraints of DHPublicKey
        if (!constraints.permits(
                EnumSet.of(CryptoPrimitive.KEY_AGREEMENT), publicKey)) {
            throw new SSLHandshakeException(
                "DHPublicKey does not comply to algorithm constraints");
        }
    } catch (GeneralSecurityException gse) {
        throw (SSLHandshakeException) new SSLHandshakeException(
                "Could not generate DHPublicKey").initCause(gse);
    }
}
 
Example #16
Source File: TimelyExceptionHandler.java    From timely with Apache License 2.0 6 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    // ignore SSLHandshakeException when using a self-signed server certificate
    if (ignoreSslHandshakeErrors && cause.getCause() instanceof SSLHandshakeException) {
        return;
    }
    LOG.error("Unhandled exception in pipeline", cause);
    if (cause instanceof TimelyException) {
        this.sendHttpError(ctx, (TimelyException) cause);
    } else if (null != cause.getCause() && cause.getCause() instanceof TimelyException) {
        this.sendHttpError(ctx, (TimelyException) cause.getCause());
    } else {
        TimelyException e = new TimelyException(HttpResponseStatus.INTERNAL_SERVER_ERROR.code(), cause.getMessage(),
                "");
        this.sendHttpError(ctx, e);
    }
}
 
Example #17
Source File: QuickConversationsService.java    From Conversations with GNU General Public License v3.0 6 votes vote down vote up
private int getApiErrorCode(final Exception e) {
    if (!service.hasInternetConnection()) {
        return API_ERROR_AIRPLANE_MODE;
    } else if (e instanceof UnknownHostException) {
        return API_ERROR_UNKNOWN_HOST;
    } else if (e instanceof ConnectException) {
        return API_ERROR_CONNECT;
    } else if (e instanceof SSLHandshakeException) {
        return API_ERROR_SSL_HANDSHAKE;
    } else if (e instanceof SSLPeerUnverifiedException || e instanceof CertificateException) {
        return API_ERROR_SSL_CERTIFICATE;
    } else if (e instanceof SSLException || e instanceof GeneralSecurityException) {
        return API_ERROR_SSL_GENERAL;
    } else if (e instanceof SocketTimeoutException) {
        return API_ERROR_TIMEOUT;
    } else {
        Log.d(Config.LOGTAG, e.getClass().getName());
        return API_ERROR_OTHER;
    }
}
 
Example #18
Source File: ProxyHandler.java    From AndServer with Apache License 2.0 5 votes vote down vote up
private Socket createSocket(HttpHost host) throws IOException {
    Socket socket = new Socket();
    socket.setSoTimeout(60 * 1000);
    socket.setReuseAddress(true);
    socket.setTcpNoDelay(true);
    socket.setKeepAlive(true);
    socket.setReceiveBufferSize(BUFFER);
    socket.setSendBufferSize(BUFFER);
    socket.setSoLinger(true, 0);

    String scheme = host.getSchemeName();
    String hostName = host.getHostName();
    int port = host.getPort();

    InetSocketAddress address = resolveAddress(scheme, hostName, port);
    socket.connect(address, 10 * 1000);

    if ("https".equalsIgnoreCase(scheme)) {
        SSLSocket sslSocket = (SSLSocket) mSocketFactory.createSocket(socket, hostName, port, true);
        try {
            sslSocket.startHandshake();
            final SSLSession session = sslSocket.getSession();
            if (session == null) {
                throw new SSLHandshakeException("SSL session not available.");
            }
        } catch (final IOException ex) {
            IOUtils.closeQuietly(sslSocket);
            throw ex;
        }
        return sslSocket;
    }
    return socket;
}
 
Example #19
Source File: SSLEngineTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Test
public void testMutualAuthDiffCertsServerFailure() throws Exception {
    File serverKeyFile = new File(getClass().getResource("test_encrypted.pem").getFile());
    File serverCrtFile = new File(getClass().getResource("test.crt").getFile());
    String serverKeyPassword = "12345";
    File clientKeyFile = new File(getClass().getResource("test2_encrypted.pem").getFile());
    File clientCrtFile = new File(getClass().getResource("test2.crt").getFile());
    String clientKeyPassword = "12345";
    // Client trusts server but server only trusts itself
    mySetupMutualAuth(serverCrtFile, serverKeyFile, serverCrtFile, serverKeyPassword,
                      serverCrtFile, clientKeyFile, clientCrtFile, clientKeyPassword);
    assertTrue(serverLatch.await(2, TimeUnit.SECONDS));
    assertTrue(serverException instanceof SSLHandshakeException);
}
 
Example #20
Source File: AbstractSingleCheckThread.java    From sitemonitoring-production with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private CloseableHttpResponse doRequest(final HttpRequestBase request) throws IOException {
	if (log.isDebugEnabled()) {
		log.debug(request.getMethod() + " " + request.getURI());
	}
	Builder requestConfigBuilder = RequestConfig.custom().setSocketTimeout(check.getSocketTimeout()).setConnectTimeout(check.getConnectionTimeout());
	if (check.getHttpProxyServer() != null && !check.getHttpProxyServer().isEmpty()) {
		HttpHost httpProxy = new HttpHost(check.getHttpProxyServer(), check.getHttpProxyPort());
		requestConfigBuilder.setProxy(httpProxy);
	}
	RequestConfig requestConfig = requestConfigBuilder.build();
	request.setConfig(requestConfig);
       String header = check.getHeader();

       if(null!=header && header.length()>0 && header.contains(":"))
       {
           log.info("header:" + header);
           String[] headerKV = header.split(":");
           request.setHeader(headerKV[0],headerKV[1]);
       }

	CloseableHttpResponse response = null;
	try {
		request.setHeader("User-Agent", check.getUserAgent());
		response = httpClient.execute(request);
	} catch (SSLHandshakeException ex) {
		// ignore ValidatorException -> thrown when Java cannot validate
		// certificate
		log.error("java could not validate certificate for URL: " + request.getURI(), ex);
		return null;
	}
	if (log.isDebugEnabled()) {
		log.debug("status: " + response.getStatusLine());
	}
	return response;
}
 
Example #21
Source File: RouteDatabase.java    From IoTgo_Android_App with MIT License 5 votes vote down vote up
/** Records a failure connecting to {@code failedRoute}. */
public synchronized void failed(Route failedRoute, IOException failure) {
  failedRoutes.add(failedRoute);

  if (!(failure instanceof SSLHandshakeException)) {
    // If the problem was not related to SSL then it will also fail with
    // a different TLS mode therefore we can be proactive about it.
    failedRoutes.add(failedRoute.flipTlsMode());
  }
}
 
Example #22
Source File: ArangoSslTest.java    From arangodb-java-driver-async with Apache License 2.0 5 votes vote down vote up
@Test
@Ignore
public void connectWithoutValidSslContext() throws Exception {
	try {
		final ArangoDBAsync arangoDB = new ArangoDBAsync.Builder()
				.loadProperties(ArangoSslTest.class.getResourceAsStream("/arangodb-ssl.properties")).useSsl(true)
				.build();
		arangoDB.getVersion().get();
		fail("this should fail");
	} catch (final ArangoDBException ex) {
		assertThat(ex.getCause() instanceof SSLHandshakeException, is(true));
	}
}
 
Example #23
Source File: ECDHCrypt.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
SecretKey getAgreedSecret(
        PublicKey peerPublicKey) throws SSLHandshakeException {

    try {
        KeyAgreement ka = JsseJce.getKeyAgreement("ECDH");
        ka.init(privateKey);
        ka.doPhase(peerPublicKey, true);
        return ka.generateSecret("TlsPremasterSecret");
    } catch (GeneralSecurityException e) {
        throw (SSLHandshakeException) new SSLHandshakeException(
            "Could not generate secret").initCause(e);
    }
}
 
Example #24
Source File: TomcatHttpsTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void wrongClientCertificateShouldFail() throws IOException, LifecycleException {
    HttpsConfig serverConfig = SecurityTestUtils.correctHttpsSettings().clientAuth(true).build();
    HttpsConfig clientConfig = SecurityTestUtils.correctHttpsSettings().keyStore(SecurityTestUtils.pathFromRepository("keystore/localhost/localhost2.keystore.p12")).build();
    try {
        startTomcatAndDoHttpsRequest(serverConfig, clientConfig);
        fail(EXPECTED_SSL_HANDSHAKE_EXCEPTION_NOT_THROWN);
    } catch (SSLHandshakeException e) {  // NOSONAR
        assertTrue(e.getMessage().contains("bad_certificate"));
    }
}
 
Example #25
Source File: SSLSocketFactoryTest.java    From TrustKit-Android with MIT License 5 votes vote down vote up
@Test
public void testPinnedDomainInvalidPin() throws IOException {
    if (Build.VERSION.SDK_INT < 17) {
        // TrustKit does not do anything for API level < 17 hence the connection will succeed
        return;
    }

    String serverHostname = "www.yahoo.com";
    TestableTrustKit.initializeWithNetworkSecurityConfiguration(
            InstrumentationRegistry.getInstrumentation().getContext(), mockReporter);

    // Create a TrustKit SocketFactory and ensure the connection fails
    SSLSocketFactory test = TestableTrustKit.getInstance().getSSLSocketFactory(serverHostname);
    boolean didReceivePinningError = false;
    try {
        test.createSocket(serverHostname, 443).getInputStream();
    } catch (SSLHandshakeException e) {
        if ((e.getCause() instanceof CertificateException
                && (e.getCause().getMessage().startsWith("Pin verification failed")))) {
            didReceivePinningError = true;
        }
    }
    assertTrue(didReceivePinningError);

    // Ensure the background reporter was called
    verify(mockReporter).pinValidationFailed(
            eq(serverHostname),
            eq(0),
            (List<X509Certificate>) org.mockito.Matchers.isNotNull(),
            (List<X509Certificate>) org.mockito.Matchers.isNotNull(),
            eq(TestableTrustKit.getInstance().getConfiguration().getPolicyForHostname(serverHostname)),
            eq(PinningValidationResult.FAILED)
    );
}
 
Example #26
Source File: ArangoSslTest.java    From arangodb-java-driver with Apache License 2.0 5 votes vote down vote up
@Test
@Ignore
public void connectWithoutValidSslContext() {
    try {
        final ArangoDB arangoDB = new ArangoDB.Builder()
                .loadProperties(ArangoSslTest.class.getResourceAsStream("/arangodb-ssl.properties")).useSsl(true)
                .build();
        arangoDB.getVersion();
        fail("this should fail");
    } catch (final ArangoDBException ex) {
        assertThat(ex.getCause() instanceof SSLHandshakeException, is(true));
    }
}
 
Example #27
Source File: DHCrypt.java    From openjdk-jdk8u 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 #28
Source File: CustomCiphersAndProtocolsSetupTest.java    From grpc-spring-boot-starter with MIT License 5 votes vote down vote up
/**
 * Tests behaviour with TLSv1.1 and shared protocols. Test should fail, as the server does not support TLSv1.1.
 */
@Test
public void testTlsV11Stub() {

    Exception exception = assertThrows(StatusRuntimeException.class, () -> {
        tlsV11Stub.normal(Empty.getDefaultInstance()).getVersion();
    });
    assertTrue(exception.getCause() instanceof SSLHandshakeException);
}
 
Example #29
Source File: TCPandSSLTransportTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoTLSv1SupportOnSSLOnlyPort() throws Exception
{
    try
    {
        checkHandshakeWithTlsProtocol("TLSv1", Transport.SSL);
        fail("Should not be able to connect using TLSv1");
    }
    catch(SSLHandshakeException e)
    {
        // pass
    }
}
 
Example #30
Source File: ECCurvesconstraints.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
void doServerSide() throws Exception {
    SSLContext context = generateSSLContext(false);
    SSLServerSocketFactory sslssf = context.getServerSocketFactory();
    SSLServerSocket sslServerSocket =
        (SSLServerSocket)sslssf.createServerSocket(serverPort);
    serverPort = sslServerSocket.getLocalPort();

    /*
     * Signal Client, we're ready for his connect.
     */
    serverReady = true;

    SSLSocket sslSocket = (SSLSocket)sslServerSocket.accept();
    try {
        sslSocket.setSoTimeout(5000);
        sslSocket.setSoLinger(true, 5);

        InputStream sslIS = sslSocket.getInputStream();
        OutputStream sslOS = sslSocket.getOutputStream();

        sslIS.read();
        sslOS.write('A');
        sslOS.flush();

        throw new Exception("EC curve secp224k1 should be disabled");
    } catch (SSLHandshakeException she) {
        // expected exception: no cipher suites in common
        System.out.println("Expected exception: " + she);
    } finally {
        sslSocket.close();
        sslServerSocket.close();
    }
}