下面列出了怎么用javax.net.ssl.SSLHandshakeException的API类实例代码及写法,或者点击链接到github查看源代码。
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();
}
@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);
}
}
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;
}
}
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);
}
}
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);
}
}
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);
}
}
}
@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));
}
}
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);
}
}
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);
}
}
}
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);
}
}
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);
}
}
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();
}
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;
}
/**
* 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;
}
}
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);
}
}
@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");
}
}
}
}
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);
}
}
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);
}
}
}
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);
}
}
@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);
}
/** */
@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
);
}
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 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");
}
}
/** 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());
}
}
private static Throwable sslException(Throwable cause) {
if (cause.getCause() != null && cause.getCause() instanceof SSLHandshakeException) {
return cause.getCause();
} else {
return null;
}
}
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);
}
}