gpt4 book ai didi

java - SSLEngine 并关闭

转载 作者:行者123 更新时间:2023-11-30 07:39:15 26 4
gpt4 key购买 nike

我已经实现了一个辅助模块,可以让我从使用 SSL 的 channel 获取干净数据并将加密数据写入其中:这是相关接口(interface)(我在该类中也有一些非抽象方法,所以没有不要对我说“DataProvider 应该是一个接口(interface)”;)):

public abstract class DataProvider {
// Notify the bytes read from the net
public abstract void readFromNet(ByteBuffer b);
// Gets the bytes to write into the net
public abstract void writeToNet(ByteBuffer b);
// Add a message to send
public abstract boolean addMessage(byte[] data);
// Obtains the application data received
public abstract byte[] getReceivedApplicationData();
// True if there is something to actually send over the wire
public abstract boolean dataToSend();
// True if we should close the channel
public abstract boolean shouldClose();
// Notify our intention to shut down the connection
public abstract void shutDown(SelectionKey sk);
// Set the interest op set for the channel
public abstract void setInterestOps(SelectionKey sk);
}

我有一个 SSL 抽象基类的实现。在测试该实现时,我编写了两个函数:在一个函数中,我使用 SocketChannel 接收一条消息,用于发送数据的 SSLSocket 关闭连接,在另一个函数中,我使用 SocketChannel 发送一条消息以启动关闭连接。现在,问题是用于接收数据的 SSLSocket 没有关闭,即使我已经执行了这些步骤:

  1. engine.closeOutbound()
  2. engine.wrap()
  3. channel.write(data)(是的,我确定我已经发送了使用 wrap() 获得的所有数据
  4. 用于读取入站 close_notify 的 channel 选择

问题是选择器卡在了第4步。

在另一个测试中(SSLSocket 关闭连接)我没有遇到问题。

请注意,我已经将 shouldClose 实现为:

return engine.isOutboundDone() && engine.isInboundDone();

所以我需要一个传入的 close_notify 才能关闭,即使我已经初始化了关闭(我不知道这是否正确:最终我可以用 return engine.isOutboundDone())

这是我的 SSLSocket 端代码:

Socket toRead = socket.accept();
toRead.setSoTimeout(0);
InputStream is = toRead.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
String read = "";
byte[] barray = new byte[1024];
while (read.length() < toSend.length() * 2) {
int bytesRead = is.read(barray);
bos.write(barray, 0, bytesRead);
read = new String(bos.toByteArray());
}
assertEquals(toSend + toSend, read);
assertTrue(toRead.isClosed());

违反了最后一个断言。

最初我认为这是因为没有与 toRead 关联的“后台”线程,所以我应该用它进行读/写以使用传入的 close_notify 然后最后关闭套接字,但即使这样也无济于事。

有什么想法吗?

最佳答案

非常晚的答复,但如果您已经发送了一个,则无需等待 close_notify,请参阅 RFC 2246。但是您应该得到一个。你没有说你在 close_notify 上选择的准确程度。

注意你的代码没有意义。套接字只有在关闭时才会关闭。 isClosed() 指的是套接字,而不是连接。

关于java - SSLEngine 并关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/921579/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com