javax.net.ssl.SSLEngine类的使用及代码示例

x33g5p2x  于2022-01-29 转载在 其他  
字(13.2k)|赞(0)|评价(0)|浏览(276)

本文整理了Java中javax.net.ssl.SSLEngine类的一些代码示例,展示了SSLEngine类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。SSLEngine类的具体详情如下:
包路径:javax.net.ssl.SSLEngine
类名称:SSLEngine

SSLEngine介绍

[英]The abstract implementation of secure communications using SSL, TLS, or other protocols. It includes the setup, handshake, and encrypt/decrypt functionality needed to create a secure connection.
[中]使用SSL、TLS或其他协议的安全通信的抽象实现。它包括建立安全连接所需的设置、握手和加密/解密功能。

代码示例

代码示例来源:origin: mrniko/netty-socketio

  1. /**
  2. * Adds the ssl handler
  3. *
  4. * @param pipeline - channel pipeline
  5. */
  6. protected void addSslHandler(ChannelPipeline pipeline) {
  7. if (sslContext != null) {
  8. SSLEngine engine = sslContext.createSSLEngine();
  9. engine.setUseClientMode(false);
  10. pipeline.addLast(SSL_HANDLER, new SslHandler(engine));
  11. }
  12. }

代码示例来源:origin: spring-projects/spring-framework

  1. @Override
  2. @Nullable
  3. protected SslInfo initSslInfo() {
  4. SslHandler sslHandler = ((Connection) this.request).channel().pipeline().get(SslHandler.class);
  5. if (sslHandler != null) {
  6. SSLSession session = sslHandler.engine().getSession();
  7. return new DefaultSslInfo(session);
  8. }
  9. return null;
  10. }

代码示例来源:origin: apache/kafka

  1. private SSLEngine createSslEngine(SSLContext sslContext, String peerHost, int peerPort) {
  2. SSLEngine sslEngine = sslContext.createSSLEngine(peerHost, peerPort);
  3. if (cipherSuites != null) sslEngine.setEnabledCipherSuites(cipherSuites);
  4. if (enabledProtocols != null) sslEngine.setEnabledProtocols(enabledProtocols);
  5. // SSLParameters#setEndpointIdentificationAlgorithm enables endpoint validation
  6. // only in client mode. Hence, validation is enabled only for clients.
  7. if (mode == Mode.SERVER) {
  8. sslEngine.setUseClientMode(false);
  9. if (needClientAuth)
  10. sslEngine.setNeedClientAuth(needClientAuth);
  11. else
  12. sslEngine.setWantClientAuth(wantClientAuth);
  13. } else {
  14. sslEngine.setUseClientMode(true);
  15. SSLParameters sslParams = sslEngine.getSSLParameters();
  16. sslParams.setEndpointIdentificationAlgorithm(endpointIdentification);
  17. sslEngine.setSSLParameters(sslParams);
  18. }
  19. return sslEngine;
  20. }

代码示例来源:origin: neo4j/neo4j

  1. /**
  2. * Apply engine modifications that will exist in any use-case of TLS
  3. *
  4. * @param sslEngine the ssl engine that will be used for the connections. Is mutated.
  5. * @return the updated sslEngine (should be the same as the original, but don't rely on that)
  6. */
  7. @Override
  8. public SSLEngine apply( SSLEngine sslEngine )
  9. {
  10. if ( tlsVersions != null )
  11. {
  12. sslEngine.setEnabledProtocols( tlsVersions );
  13. }
  14. sslEngine.setUseClientMode( isClient );
  15. return sslEngine;
  16. }
  17. }

代码示例来源:origin: apache/kafka

  1. private SSLConfigValidatorEngine(SslFactory sslFactory, SSLContext sslContext, Mode mode) {
  2. this.sslEngine = sslFactory.createSslEngine(sslContext, "localhost", 0); // these hints are not used for validation
  3. sslEngine.setUseClientMode(mode == Mode.CLIENT);
  4. appBuffer = ByteBuffer.allocate(sslEngine.getSession().getApplicationBufferSize());
  5. netBuffer = ByteBuffer.allocate(sslEngine.getSession().getPacketBufferSize());
  6. }

代码示例来源:origin: Netflix/zuul

  1. if (sslEvent.isSuccess()) {
  2. CurrentPassport.fromChannel(ctx.channel()).add(PassportState.SERVER_CH_SSL_HANDSHAKE_COMPLETE);
  3. SslHandler sslhandler = (SslHandler) ctx.channel().pipeline().get("ssl");
  4. SSLSession session = sslhandler.engine().getSession();
  5. && session.getPeerCertificateChain() != null && session.getPeerCertificateChain().length > 0) {
  6. peerCert = session.getPeerCertificateChain()[0];
  7. if (session.getLocalCertificates() != null && session.getLocalCertificates().length > 0) {
  8. SslHandshakeInfo info = new SslHandshakeInfo(isSSlFromIntermediary, session.getProtocol(), session.getCipherSuite(), clientAuth, serverCert, peerCert);
  9. ctx.channel().attr(ATTR_SSL_INFO).set(info);
  10. String clientIP = ctx.channel().attr(SourceAddressChannelHandler.ATTR_SOURCE_ADDRESS).get();
  11. Throwable cause = sslEvent.cause();
  12. ctx.pipeline().remove(this);

代码示例来源:origin: apache/nifi

  1. public SSLSocketChannel(final SSLContext sslContext, final SocketChannel socketChannel, final boolean client) throws IOException {
  2. if (!socketChannel.isConnected()) {
  3. throw new IllegalArgumentException("Cannot pass an un-connected SocketChannel");
  4. }
  5. this.channel = socketChannel;
  6. this.socketAddress = socketChannel.getRemoteAddress();
  7. final Socket socket = socketChannel.socket();
  8. this.hostname = socket.getInetAddress().getHostName();
  9. this.port = socket.getPort();
  10. this.engine = sslContext.createSSLEngine();
  11. this.engine.setUseClientMode(client);
  12. this.engine.setNeedClientAuth(true);
  13. streamInManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getPacketBufferSize()));
  14. streamOutManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getPacketBufferSize()));
  15. appDataManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getApplicationBufferSize()));
  16. }

代码示例来源:origin: apache/nifi

  1. public SSLSocketChannel(final SSLContext sslContext, final String hostname, final int port, final InetAddress localAddress, final boolean client) throws IOException {
  2. this.socketAddress = new InetSocketAddress(hostname, port);
  3. this.channel = SocketChannel.open();
  4. if (localAddress != null) {
  5. final SocketAddress localSocketAddress = new InetSocketAddress(localAddress, 0);
  6. this.channel.bind(localSocketAddress);
  7. }
  8. this.hostname = hostname;
  9. this.port = port;
  10. this.engine = sslContext.createSSLEngine();
  11. this.engine.setUseClientMode(client);
  12. engine.setNeedClientAuth(true);
  13. streamInManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getPacketBufferSize()));
  14. streamOutManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getPacketBufferSize()));
  15. appDataManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getApplicationBufferSize()));
  16. }

代码示例来源:origin: Netflix/zuul

  1. @Override
  2. protected void initChannel(Channel ch) throws Exception
  3. {
  4. SslHandler sslHandler = sslContext.newHandler(ch.alloc());
  5. sslHandler.engine().setEnabledProtocols(sslContextFactory.getProtocols());
  6. // Configure our pipeline of ChannelHandlerS.
  7. ChannelPipeline pipeline = ch.pipeline();
  8. storeChannel(ch);
  9. addTimeoutHandlers(pipeline);
  10. addPassportHandler(pipeline);
  11. addTcpRelatedHandlers(pipeline);
  12. pipeline.addLast("ssl", sslHandler);
  13. addSslInfoHandlers(pipeline, isSSlFromIntermediary);
  14. addSslClientCertChecks(pipeline);
  15. addHttp1Handlers(pipeline);
  16. addHttpRelatedHandlers(pipeline);
  17. addZuulHandlers(pipeline);
  18. }
  19. }

代码示例来源:origin: apache/pulsar

  1. ChannelHandler sslHandler = ctx.channel().pipeline().get("tls");
  2. sslSession = ((SslHandler) sslHandler).engine().getSession();
  3. if (log.isDebugEnabled()) {
  4. log.debug("Verifying HostName for {}, Cipher {}, Protocols {}", hostname, sslSession.getCipherSuite(),
  5. sslSession.getProtocol());

代码示例来源:origin: apache/geode

  1. @Test
  2. public void closeWhenUnwrapError() throws Exception {
  3. SocketChannel mockChannel = mock(SocketChannel.class);
  4. Socket mockSocket = mock(Socket.class);
  5. when(mockChannel.socket()).thenReturn(mockSocket);
  6. when(mockSocket.isClosed()).thenReturn(true);
  7. when(mockEngine.isOutboundDone()).thenReturn(Boolean.FALSE);
  8. when(mockEngine.wrap(any(ByteBuffer.class), any(ByteBuffer.class))).thenReturn(
  9. new SSLEngineResult(BUFFER_OVERFLOW, FINISHED, 0, 0));
  10. assertThatThrownBy(() -> nioSslEngine.close(mockChannel)).isInstanceOf(GemFireIOException.class)
  11. .hasMessageContaining("exception closing SSL session")
  12. .hasCauseInstanceOf(SSLException.class);
  13. }

代码示例来源:origin: apache/kafka

  1. void handshake(SSLConfigValidatorEngine peerEngine) throws SSLException {
  2. SSLEngineResult.HandshakeStatus handshakeStatus = sslEngine.getHandshakeStatus();
  3. while (true) {
  4. switch (handshakeStatus) {
  5. case NEED_WRAP:
  6. handshakeResult = sslEngine.wrap(EMPTY_BUF, netBuffer);
  7. switch (handshakeResult.getStatus()) {
  8. case OK: break;
  9. case BUFFER_OVERFLOW:
  10. netBuffer.compact();
  11. netBuffer = Utils.ensureCapacity(netBuffer, sslEngine.getSession().getPacketBufferSize());
  12. netBuffer.flip();
  13. break;
  14. handshakeResult = sslEngine.unwrap(peerEngine.netBuffer, appBuffer);
  15. peerEngine.netBuffer.compact();
  16. handshakeStatus = handshakeResult.getHandshakeStatus();
  17. case BUFFER_OVERFLOW:
  18. appBuffer = Utils.ensureCapacity(appBuffer, sslEngine.getSession().getApplicationBufferSize());
  19. break;
  20. case BUFFER_UNDERFLOW:
  21. netBuffer = Utils.ensureCapacity(netBuffer, sslEngine.getSession().getPacketBufferSize());
  22. break;
  23. case CLOSED:
  24. default:
  25. throw new SSLException("Unexpected handshake status: " + handshakeResult.getStatus());
  26. sslEngine.getDelegatedTask().run();
  27. handshakeStatus = sslEngine.getHandshakeStatus();

代码示例来源:origin: apache/nifi

  1. engine.closeOutbound();
  2. final ByteBuffer outboundBuffer = streamOutManager.prepareForWrite(engine.getSession().getApplicationBufferSize());
  3. final SSLEngineResult handshakeResult = engine.wrap(appDataOut, outboundBuffer);
  4. if (handshakeResult.getStatus() != Status.CLOSED) {
  5. throw new IOException("Invalid close state - will not send network data");
  6. int bytesDiscarded = channel.read(discardBuffer);
  7. while (bytesDiscarded > 0) {
  8. discardBuffer.clear();
  9. bytesDiscarded = channel.read(discardBuffer);
  10. closeQuietly(channel.socket());
  11. closeQuietly(channel);
  12. closed = true;

代码示例来源:origin: TooTallNate/Java-WebSocket

  1. public void close() throws IOException {
  2. sslEngine.closeOutbound();
  3. sslEngine.getSession().invalidate();
  4. if( socketChannel.isOpen() )
  5. socketChannel.write( wrap( emptybuffer ) );// FIXME what if not all bytes can be written
  6. socketChannel.close();
  7. }

代码示例来源:origin: apache/kafka

  1. if (state == State.CLOSING) return;
  2. state = State.CLOSING;
  3. sslEngine.closeOutbound();
  4. try {
  5. if (prevState != State.NOT_INITALIZED && isConnected()) {
  6. SSLEngineResult wrapResult = sslEngine.wrap(emptyBuf, netWriteBuffer);
  7. if (wrapResult.getStatus() != SSLEngineResult.Status.CLOSED) {
  8. throw new IOException("Unexpected status returned by SSLEngine.wrap, expected CLOSED, received " +
  9. wrapResult.getStatus() + ". Will not send close message to peer.");
  10. log.debug("Failed to send SSL Close message", ie);
  11. } finally {
  12. socketChannel.socket().close();
  13. socketChannel.close();
  14. netReadBuffer = null;
  15. netWriteBuffer = null;

代码示例来源:origin: apache/flume

  1. private Optional<SSLEngine> getSslEngine(boolean useClientMode) {
  2. return getSslContext().map(sslContext -> {
  3. SSLEngine sslEngine = sslContext.createSSLEngine();
  4. sslEngine.setUseClientMode(useClientMode);
  5. sslEngine.setEnabledProtocols(
  6. getFilteredProtocols(sslEngine.getEnabledProtocols()));
  7. sslEngine.setEnabledCipherSuites(
  8. getFilteredCipherSuites(sslEngine.getEnabledCipherSuites()));
  9. return sslEngine;
  10. });
  11. }

代码示例来源:origin: apache/geode

  1. @Test
  2. public void handshakeDoesNotTerminateWithFinished() throws Exception {
  3. SocketChannel mockChannel = mock(SocketChannel.class);
  4. when(mockChannel.read(any(ByteBuffer.class))).thenReturn(100, 100, 100, 0);
  5. Socket mockSocket = mock(Socket.class);
  6. when(mockChannel.socket()).thenReturn(mockSocket);
  7. when(mockSocket.isClosed()).thenReturn(false);
  8. // initial read of handshake status followed by read of handshake status after task execution
  9. when(mockEngine.getHandshakeStatus()).thenReturn(NEED_UNWRAP);
  10. // interleaved wraps/unwraps/task-execution
  11. when(mockEngine.unwrap(any(ByteBuffer.class), any(ByteBuffer.class))).thenReturn(
  12. new SSLEngineResult(OK, NEED_WRAP, 100, 100));
  13. when(mockEngine.wrap(any(ByteBuffer.class), any(ByteBuffer.class))).thenReturn(
  14. new SSLEngineResult(CLOSED, NOT_HANDSHAKING, 100, 0));
  15. ByteBuffer byteBuffer = ByteBuffer.allocate(netBufferSize);
  16. assertThatThrownBy(() -> spyNioSslEngine.handshake(mockChannel, 10000, byteBuffer))
  17. .isInstanceOf(
  18. SSLHandshakeException.class)
  19. .hasMessageContaining("SSL Handshake terminated with status");
  20. }

代码示例来源:origin: apache/nifi

  1. public SSLSocketChannel(final SSLEngine sslEngine, final SocketChannel socketChannel) throws IOException {
  2. if (!socketChannel.isConnected()) {
  3. throw new IllegalArgumentException("Cannot pass an un-connected SocketChannel");
  4. }
  5. this.channel = socketChannel;
  6. this.socketAddress = socketChannel.getRemoteAddress();
  7. final Socket socket = socketChannel.socket();
  8. this.hostname = socket.getInetAddress().getHostName();
  9. this.port = socket.getPort();
  10. // don't set useClientMode or needClientAuth, use the engine as is and let the caller configure it
  11. this.engine = sslEngine;
  12. streamInManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getPacketBufferSize()));
  13. streamOutManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getPacketBufferSize()));
  14. appDataManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getApplicationBufferSize()));
  15. }

代码示例来源:origin: apache/geode

  1. private void createIoFilter(SocketChannel channel, boolean clientSocket) throws IOException {
  2. if (getConduit().useSSL() && channel != null) {
  3. InetSocketAddress address = (InetSocketAddress) channel.getRemoteAddress();
  4. SSLEngine engine =
  5. getConduit().getSocketCreator().createSSLEngine(address.getHostName(), address.getPort());
  6. if (!clientSocket) {
  7. engine.setWantClientAuth(true);
  8. engine.setNeedClientAuth(true);
  9. }
  10. int packetBufferSize = engine.getSession().getPacketBufferSize();
  11. if (inputBuffer == null
  12. || (inputBuffer.capacity() < packetBufferSize)) {
  13. // TLS has a minimum input buffer size constraint
  14. if (inputBuffer != null) {
  15. Buffers.releaseReceiveBuffer(inputBuffer, getConduit().getStats());
  16. }
  17. inputBuffer = Buffers.acquireReceiveBuffer(packetBufferSize, getConduit().getStats());
  18. }
  19. if (channel.socket().getReceiveBufferSize() < packetBufferSize) {
  20. channel.socket().setReceiveBufferSize(packetBufferSize);
  21. }
  22. if (channel.socket().getSendBufferSize() < packetBufferSize) {
  23. channel.socket().setSendBufferSize(packetBufferSize);
  24. }
  25. ioFilter = getConduit().getSocketCreator().handshakeSSLSocketChannel(channel, engine,
  26. getConduit().idleConnectionTimeout, clientSocket, inputBuffer, getConduit().getStats());
  27. } else {
  28. ioFilter = new NioPlainEngine();
  29. }
  30. }

代码示例来源:origin: TooTallNate/Java-WebSocket

  1. @Override
  2. public ByteChannel wrapChannel(SocketChannel channel, SelectionKey key) throws IOException {
  3. SSLEngine e = sslcontext.createSSLEngine();
  4. if (enabledProtocols != null) {
  5. e.setEnabledProtocols(enabledProtocols);
  6. }
  7. if (enabledCiphersuites != null) {
  8. e.setEnabledCipherSuites(enabledCiphersuites);
  9. }
  10. e.setUseClientMode(false);
  11. return new SSLSocketChannel2(channel, e, exec, key);
  12. }

相关文章