下面列出了javax.net.ssl.SSLException#printStackTrace ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static SslContext getSslContext(){
ClassLoader classLoader = AlphaIntegrationWithSSLTest.class.getClassLoader();
SslContext sslContext = null;
try {
sslContext = GrpcSslContexts.forClient().sslProvider(SslProvider.OPENSSL)
.protocols("TLSv1.2","TLSv1.1")
.ciphers(Arrays.asList("ECDHE-RSA-AES128-GCM-SHA256",
"ECDHE-RSA-AES256-GCM-SHA384",
"ECDHE-ECDSA-AES128-SHA256"))
.trustManager(new File(classLoader.getResource("ca.crt").getFile()))
.keyManager(new File(classLoader.getResource("client.crt").getFile()),
new File(classLoader.getResource("client.pem").getFile())).build();
} catch (SSLException e) {
e.printStackTrace();
}
return sslContext;
}
private SslContext buildSslCtx() {
SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;
try {
return SslContextBuilder.forClient()
.sslProvider(provider)
.ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
.trustManager(InsecureTrustManagerFactory.INSTANCE)
// TODO(JR): Make a seperate Handler Class for http2 as opposed to autoneg
// .applicationProtocolConfig(new ApplicationProtocolConfig(
// ApplicationProtocolConfig.Protocol.ALPN,
// // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK
// providers.
// ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
// // ACCEPT is currently the only mode supported by both OpenSsl and JDK
// providers.
// ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
// ApplicationProtocolNames.HTTP_2,
// ApplicationProtocolNames.HTTP_1_1))
.build();
} catch (SSLException e) {
e.printStackTrace();
}
return null;
}
@Specialization(guards = {"sourceBuffer.isByteType()", "targetBuffer.isByteType()"})
protected static final long doConnect(@SuppressWarnings("unused") final Object receiver,
final PointersObject sslHandle,
final NativeObject sourceBuffer,
final long start,
final long length,
final NativeObject targetBuffer,
@CachedContext(SqueakLanguage.class) final SqueakImageContext image) {
final SqSSL ssl = getSSLOrNull(sslHandle);
if (ssl == null) {
return ReturnCode.INVALID_STATE.id();
}
final ByteBuffer source = asReadBuffer(sourceBuffer, start, length);
final ByteBuffer target = asWriteBuffer(targetBuffer);
try {
return processHandshake(ssl, source, target);
} catch (final SSLException e) {
e.printStackTrace(image.getError());
return ReturnCode.GENERIC_ERROR.id();
}
}
@Specialization(guards = {"sourceBuffer.isByteType()", "targetBuffer.isByteType()"})
protected static final long doEncrypt(@SuppressWarnings("unused") final Object receiver,
final PointersObject sslHandle,
final NativeObject sourceBuffer,
final long start,
final long length,
final NativeObject targetBuffer,
@CachedContext(SqueakLanguage.class) final SqueakImageContext image) {
final SqSSL ssl = getSSLOrNull(sslHandle);
if (ssl == null) {
return ReturnCode.INVALID_STATE.id();
}
final ByteBuffer source = asReadBuffer(sourceBuffer, start, length);
final ByteBuffer target = asWriteBuffer(targetBuffer);
try {
encrypt(ssl, source, target);
return target.position();
} catch (final SSLException e) {
e.printStackTrace(image.getError());
return ReturnCode.GENERIC_ERROR.id();
}
}
private static SslContext getSslContext(){
ClassLoader classLoader = AlphaIntegrationWithSSLTest.class.getClassLoader();
SslContext sslContext = null;
try {
sslContext = GrpcSslContexts.forClient().sslProvider(SslProvider.OPENSSL)
.protocols("TLSv1.2","TLSv1.1")
.ciphers(Arrays.asList("ECDHE-RSA-AES128-GCM-SHA256",
"ECDHE-RSA-AES256-GCM-SHA384"))
.trustManager(new File(classLoader.getResource("ca.crt").getFile()))
.keyManager(new File(classLoader.getResource("client.crt").getFile()),
new File(classLoader.getResource("client.pem").getFile())).build();
} catch (SSLException e) {
e.printStackTrace();
}
return sslContext;
}
public NettyHttpClient(String authCode, HttpProxy proxy, ClientConfig config) {
_maxRetryTimes = config.getMaxRetryTimes();
_readTimeout = config.getReadTimeout();
String message = MessageFormat.format("Created instance with "
+ "connectionTimeout {0}, readTimeout {1}, maxRetryTimes {2}, SSL Version {3}",
config.getConnectionTimeout(), _readTimeout, _maxRetryTimes, config.getSSLVersion());
LOG.debug(message);
_authCode = authCode;
_encryptType = config.getEncryptType();
try {
_sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
_workerGroup = new NioEventLoopGroup();
b = new Bootstrap(); // (1)
b.group(_workerGroup); // (2)
b.channel(NioSocketChannel.class); // (3)
b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
} catch (SSLException e) {
e.printStackTrace();
}
}
/**
* Verifies that the certificate matches the specified hostname.
* Uses the {@link DefaultHostnameVerifier} from the Apache HttpClient library
* to confirm that the hostname matches the certificate.
*
* @param hostname
* @param leafCert
* @return
*/
private static boolean verifyHostname(String hostname, X509Certificate leafCert) {
try {
// Check that the hostname matches the certificate. This method throws an exception if
// the cert could not be verified.
HOSTNAME_VERIFIER.verify(hostname, leafCert);
return true;
} catch (SSLException e) {
e.printStackTrace();
}
return false;
}
public static void main(String[] args) throws Exception {
SslContext sslCtx = null;
try {
File certChainFile = new File("netty.crt");
File keyFile = new File("privatekey.pem");
keyFile.exists();
sslCtx = SslContext.newServerContext(certChainFile, keyFile, "1234");
}
catch (SSLException e) {
e.printStackTrace();
System.out.println("Can not create SSL context! \n Server will be stop!");
}
// Configure the server.
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new HttpSnoopServerInitializer(sslCtx));
Channel ch = b.bind(PORT).sync().channel();
ch.closeFuture().sync();
}
finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public void testNeedClientAuthReject() throws Exception {
SSLContext context = SSLContext.getInstance("TLS");
// no client cert
context.init(null, getTrustManager(), null);
try {
makeSSLConnection(context, null, needClientAuthConnector);
fail("expected failure on no client cert");
} catch (SSLException expected) {
expected.printStackTrace();
}
// should work with regular connector
makeSSLConnection(context, null, connector);
}
public SlackSender() {
try {
sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
bootstrap.group(group)
.channel(Epoll.isAvailable() ? EpollSocketChannel.class : NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.option(ChannelOption.SO_KEEPALIVE, true);
} catch (SSLException e) {
e.printStackTrace();
}
}
private void doTestCustomTrustManager(TrustType trustType)
throws Exception {
Tomcat tomcat = getTomcatInstance();
Assume.assumeTrue("SSL renegotiation has to be supported for this test",
TesterSupport.isRenegotiationSupported(getTomcatInstance()));
TesterSupport.configureClientCertContext(tomcat);
// Override the defaults
ProtocolHandler handler = tomcat.getConnector().getProtocolHandler();
if (handler instanceof AbstractHttp11JsseProtocol) {
((AbstractHttp11JsseProtocol<?>) handler).setTruststoreFile(null);
} else {
// Unexpected
Assert.fail("Unexpected handler type");
}
if (trustType.equals(TrustType.ALL)) {
tomcat.getConnector().setAttribute("trustManagerClassName",
"org.apache.tomcat.util.net.TesterSupport$TrustAllCerts");
} else if (trustType.equals(TrustType.CA)) {
tomcat.getConnector().setAttribute("trustManagerClassName",
"org.apache.tomcat.util.net.TesterSupport$SequentialTrustManager");
}
// Start Tomcat
tomcat.start();
TesterSupport.configureClientSsl();
// Unprotected resource
ByteChunk res =
getUrl("https://localhost:" + getPort() + "/unprotected");
Assert.assertEquals("OK", res.toString());
// Protected resource
res.recycle();
int rc = -1;
try {
rc = getUrl("https://localhost:" + getPort() + "/protected", res,
null, null);
} catch (SocketException se) {
if (!trustType.equals(TrustType.NONE)) {
Assert.fail(se.getMessage());
se.printStackTrace();
}
} catch (SSLException he) {
if (!trustType.equals(TrustType.NONE)) {
Assert.fail(he.getMessage());
he.printStackTrace();
}
}
if (trustType.equals(TrustType.CA)) {
if (log.isDebugEnabled()) {
int count = TesterSupport.getLastClientAuthRequestedIssuerCount();
log.debug("Last client KeyManager usage: " + TesterSupport.getLastClientAuthKeyManagerUsage() +
", " + count + " requested Issuers, first one: " +
(count > 0 ? TesterSupport.getLastClientAuthRequestedIssuer(0).getName() : "NONE"));
log.debug("Expected requested Issuer: " + TesterSupport.getClientAuthExpectedIssuer());
}
Assert.assertTrue("Checking requested client issuer against " +
TesterSupport.getClientAuthExpectedIssuer(),
TesterSupport.checkLastClientAuthRequestedIssuers());
}
if (trustType.equals(TrustType.NONE)) {
Assert.assertTrue(rc != 200);
Assert.assertEquals("", res.toString());
} else {
Assert.assertEquals(200, rc);
Assert.assertEquals("OK-" + TesterSupport.ROLE, res.toString());
}
}
@Override
public synchronized int read(ByteBuffer dst) throws IOException {
if (!dst.hasRemaining()) {
return 0;
}
if (peerAppData.hasRemaining()) {
peerAppData.flip();
return ByteBufferUtils.transferByteBuffer(peerAppData, dst);
}
peerNetData.compact();
int bytesRead = socketChannel.read(peerNetData);
/*
* If bytesRead are 0 put we still have some data in peerNetData still to an unwrap (for
* testcase 1.1.6)
*/
if (bytesRead > 0 || peerNetData.hasRemaining()) {
peerNetData.flip();
while (peerNetData.hasRemaining()) {
peerAppData.compact();
SSLEngineResult result;
try {
result = engine.unwrap(peerNetData, peerAppData);
} catch (SSLException e) {
e.printStackTrace();
throw e;
}
switch (result.getStatus()) {
case OK:
peerAppData.flip();
return ByteBufferUtils.transferByteBuffer(peerAppData, dst);
case BUFFER_UNDERFLOW:
peerAppData.flip();
return ByteBufferUtils.transferByteBuffer(peerAppData, dst);
case BUFFER_OVERFLOW:
peerAppData = enlargeApplicationBuffer(peerAppData);
break;
case CLOSED:
closeConnection();
dst.clear();
return -1;
default:
throw new IllegalStateException("Invalid SSL status: " + result.getStatus());
}
}
} else if (bytesRead < 0) {
handleEndOfStream();
}
ByteBufferUtils.transferByteBuffer(peerAppData, dst);
return bytesRead;
}
private void doTestCustomTrustManager(boolean serverTrustAll)
throws Exception {
if (!TesterSupport.RFC_5746_SUPPORTED) {
// Make sure SSL renegotiation is not disabled in the JVM
System.setProperty("sun.security.ssl.allowUnsafeRenegotiation",
"true");
}
Tomcat tomcat = getTomcatInstance();
Assume.assumeTrue("SSL renegotiation has to be supported for this test",
TesterSupport.isRenegotiationSupported(getTomcatInstance()));
TesterSupport.configureClientCertContext(tomcat);
// Override the defaults
ProtocolHandler handler = tomcat.getConnector().getProtocolHandler();
if (handler instanceof AbstractHttp11JsseProtocol) {
((AbstractHttp11JsseProtocol<?>) handler).setTruststoreFile(null);
} else {
// Unexpected
fail("Unexpected handler type");
}
if (serverTrustAll) {
tomcat.getConnector().setAttribute("trustManagerClassName",
"org.apache.tomcat.util.net.TesterSupport$TrustAllCerts");
}
// Start Tomcat
tomcat.start();
TesterSupport.configureClientSsl();
// Unprotected resource
ByteChunk res =
getUrl("https://localhost:" + getPort() + "/unprotected");
assertEquals("OK", res.toString());
// Protected resource
res.recycle();
int rc = -1;
try {
rc = getUrl("https://localhost:" + getPort() + "/protected", res,
null, null);
} catch (SocketException se) {
if (serverTrustAll) {
fail(se.getMessage());
se.printStackTrace();
}
} catch (SSLException he) {
if (serverTrustAll) {
fail(he.getMessage());
he.printStackTrace();
}
}
if (serverTrustAll) {
assertEquals(200, rc);
assertEquals("OK-" + TesterSupport.ROLE, res.toString());
} else {
assertTrue(rc != 200);
assertEquals("", res.toString());
}
}
private void doTestCustomTrustManager(boolean serverTrustAll)
throws Exception {
if (!TesterSupport.RFC_5746_SUPPORTED) {
// Make sure SSL renegotiation is not disabled in the JVM
System.setProperty("sun.security.ssl.allowUnsafeRenegotiation",
"true");
}
Tomcat tomcat = getTomcatInstance();
Assume.assumeTrue("SSL renegotiation has to be supported for this test",
TesterSupport.isRenegotiationSupported(getTomcatInstance()));
TesterSupport.configureClientCertContext(tomcat);
// Override the defaults
ProtocolHandler handler = tomcat.getConnector().getProtocolHandler();
if (handler instanceof AbstractHttp11JsseProtocol) {
((AbstractHttp11JsseProtocol<?>) handler).setTruststoreFile(null);
} else {
// Unexpected
fail("Unexpected handler type");
}
if (serverTrustAll) {
tomcat.getConnector().setAttribute("trustManagerClassName",
"org.apache.tomcat.util.net.TesterSupport$TrustAllCerts");
}
// Start Tomcat
tomcat.start();
TesterSupport.configureClientSsl();
// Unprotected resource
ByteChunk res =
getUrl("https://localhost:" + getPort() + "/unprotected");
assertEquals("OK", res.toString());
// Protected resource
res.recycle();
int rc = -1;
try {
rc = getUrl("https://localhost:" + getPort() + "/protected", res,
null, null);
} catch (SocketException se) {
if (serverTrustAll) {
fail(se.getMessage());
se.printStackTrace();
}
} catch (SSLException he) {
if (serverTrustAll) {
fail(he.getMessage());
he.printStackTrace();
}
}
if (serverTrustAll) {
assertEquals(200, rc);
assertEquals("OK-" + TesterSupport.ROLE, res.toString());
} else {
assertTrue(rc != 200);
assertEquals("", res.toString());
}
}