类javax.net.ssl.SSLHandshakeException源码实例Demo

下面列出了怎么用javax.net.ssl.SSLHandshakeException的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: jdk8u-jdk   文件: JConsole.java
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();
}
 
源代码2 项目: timely   文件: TimelyExceptionHandler.java
@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);
    }
}
 
源代码3 项目: Conversations   文件: QuickConversationsService.java
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;
    }
}
 
源代码4 项目: openjdk-jdk9   文件: DHCrypt.java
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);
    }
}
 
源代码5 项目: jdk8u_jdk   文件: ECDHCrypt.java
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);
    }
}
 
源代码6 项目: jdk8u60   文件: JMXStartStopTest.java
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);
        }
    }
}
 
源代码7 项目: openjsse   文件: SSLTrafficKeyDerivation.java
@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));
    }
}
 
源代码8 项目: openjsse   文件: ECDHKeyExchange.java
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);
    }
}
 
源代码9 项目: hottub   文件: JMXStartStopTest.java
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);
        }
    }
}
 
源代码10 项目: dragonwell8_jdk   文件: DHCrypt.java
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);
    }
}
 
源代码11 项目: dragonwell8_jdk   文件: ECDHCrypt.java
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);
    }
}
 
源代码12 项目: jdk8u60   文件: JConsole.java
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();
}
 
源代码13 项目: dropbox-sdk-java   文件: NetworkIOException.java
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;
}
 
源代码14 项目: firebase-android-sdk   文件: Datastore.java
/**
 * 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;
}
 
@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;
    }
}
 
源代码16 项目: jdk8u60   文件: DHCrypt.java
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);
    }
}
 
源代码17 项目: Bytecoder   文件: CertificateStatus.java
@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);
    }
}
 
@Override
public Answer<String> getAnswerForRequestStringFromServer() {
    return new Answer<String>() {
        @Override
        public String answer(InvocationOnMock invocation) throws Throwable {
            String url = (String) invocation.getArguments()[0];
            String requestMethod = (String) invocation.getArguments()[1];
            String jsonPayload = (String) invocation.getArguments()[2];

            if (url.contains("/provider.json")) {
                //download provider json
                return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.net.json"));
            } else if (url.contains("/ca.crt")) {
                //download provider ca cert
                return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.net.pem"));
            } else if (url.contains("config/eip-service.json")) {
                // download provider service json containing gateways, locations and openvpn settings
                throw new SSLHandshakeException("Invalid provider CA certificate");
            } else if (url.contains("/users.json")) {
                //create new user
                //TODO: implement me
            } else if (url.contains("/sessions.json")) {
                //srp auth: sendAToSRPServer
                //TODO: implement me
            } else if (url.contains("/sessions/parmegvtest10.json")){
                //srp auth: sendM1ToSRPServer
                //TODO: implement me
            }

            return null;
        }
    };
}
 
private boolean isRecoverable(IOException e) {
  // If the problem was a CertificateException from the X509TrustManager,
  // do not retry, we didn't have an abrupt server initiated exception.
  boolean sslFailure =
      e instanceof SSLHandshakeException && e.getCause() instanceof CertificateException;
  boolean protocolFailure = e instanceof ProtocolException;
  return !sslFailure && !protocolFailure;
}
 
@Test
public void testPemClientAuthFailure() throws Exception {

    try (TestServer testServer = new TestServer("sslConfigurator/pem/truststore.jks",
            "sslConfigurator/pem/node1-keystore.jks", "secret", true)) {
        Path rootCaPemPath = FileHelper.getAbsoluteFilePathFromClassPath("sslConfigurator/pem/root-ca.pem");

        Settings settings = Settings.builder()
                .put("prefix.pemtrustedcas_filepath", rootCaPemPath.getFileName().toString())
                .put("prefix.enable_ssl", "true").put("path.home", rootCaPemPath.getParent().toString())
                .put("prefix.enable_ssl_client_auth", "true").put("prefix.pemcert_filepath", "wrong-kirk.pem")
                .put("prefix.pemkey_filepath", "wrong-kirk.key").put("prefix.pemkey_password", "G0CVtComen4a")
                .build();
        Path configPath = rootCaPemPath.getParent();

        SettingsBasedSSLConfigurator sbsc = new SettingsBasedSSLConfigurator(settings, configPath, "prefix");

        SSLConfig sslConfig = sbsc.buildSSLConfig();

        try (CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(sslConfig.toSSLConnectionSocketFactory()).build()) {

            // Due to some race condition in Java's internal network stack, this can be one
            // of the following exceptions

            thrown.expect(either(instanceOf(SocketException.class)).or(instanceOf(SSLHandshakeException.class))
                    .or(instanceOf(SSLException.class)) // Java 11: javax.net.ssl.SSLException: readHandshakeRecord
            );

            try (CloseableHttpResponse response = httpClient.execute(new HttpGet(testServer.getUri()))) {
                Assert.fail("Connection should have failed due to wrong client cert");
            }
        }
    }
}
 
源代码21 项目: Bytecoder   文件: ECDHKeyExchange.java
SecretKey getAgreedSecret(
        PublicKey peerPublicKey) throws SSLHandshakeException {

    try {
        KeyAgreement ka = KeyAgreement.getInstance("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);
    }
}
 
源代码22 项目: quarkus   文件: KubernetesClientErrorHanlder.java
public static void handle(Exception e) {
    if (e.getCause() instanceof SSLHandshakeException) {
        LOG.error(
                "The application could not be deployed to the cluster because the Kubernetes API Server certificates are not trusted. The certificates can be configured using the relevant configuration propertiers under the 'quarkus.kubernetes-client' config root, or \"quarkus.kubernetes-client.trust-certs=true\" can be set to explicitly trust the certificates (not recommended)");
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        } else {
            throw new RuntimeException(e);
        }
    }
}
 
源代码23 项目: TencentKona-8   文件: ECDHCrypt.java
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);
    }
}
 
源代码24 项目: vertx-mail-client   文件: MailSslTest.java
@Test
public void mailTestSSLNoTrust(TestContext testContext) {
  this.testContext = testContext;
  startServer(SERVER2_JKS);
  final MailConfig config = new MailConfig("localhost", 1465, StartTLSOptions.DISABLED, LoginOption.DISABLED)
      .setSsl(true);
  MailClient mailClient = MailClient.create(vertx, config);
  testException(mailClient, SSLHandshakeException.class);
}
 
源代码25 项目: ignite   文件: RestExecutorSelfTest.java
/** */
 @Test
 public void differentCiphers1() throws Exception {
     ruleForExpectedException.expect(SSLHandshakeException.class);
     checkRest(
         nodeConfiguration(JETTY_WITH_CIPHERS_1),
         HTTPS_URI,
         resolvePath("client.jks"), "123456",
         resolvePath("ca.jks"), "123456",
         CIPHER_2
     );
}
 
源代码26 项目: reader   文件: HttpURLConnectionImpl.java
private boolean isRecoverable(IOException e) {
  // If the problem was a CertificateException from the X509TrustManager,
  // do not retry, we didn't have an abrupt server initiated exception.
  boolean sslFailure =
      e instanceof SSLHandshakeException && e.getCause() instanceof CertificateException;
  boolean protocolFailure = e instanceof ProtocolException;
  return !sslFailure && !protocolFailure;
}
 
源代码27 项目: qpid-broker-j   文件: TCPandSSLTransportTest.java
@Test
public void testTLSv1_3SupportOnSSLOnlyPort() throws Exception
{
    assumeThat("Java 11 or above is required", isJava11OrAbove(), is(true));
    try
    {
        checkHandshakeWithTlsProtocol("TLSv1.3", Transport.SSL);
    }
    catch(SSLHandshakeException e)
    {
        LOGGER.error("Should be able to connect using TLSv1.3", e);
        fail("Should be able to connect using TLSv1.3");
    }
}
 
源代码28 项目: reader   文件: RouteDatabase.java
/** 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());
  }
}
 
源代码29 项目: styx   文件: HttpPipelineHandler.java
private static Throwable sslException(Throwable cause) {
    if (cause.getCause() != null && cause.getCause() instanceof SSLHandshakeException) {
        return cause.getCause();
    } else {
        return null;
    }
}
 
源代码30 项目: jdk8u_jdk   文件: ECDHCrypt.java
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);
    }
}