net_io.core.ssl.SSLSocketEngine Maven / Gradle / Ivy
The newest version!
package net_io.core.ssl;
import java.io.IOException;
import java.nio.ByteBuffer;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
import javax.net.ssl.SSLEngineResult.Status;
import javax.net.ssl.SSLException;
import net_io.core.ByteBufferPool;
class SSLSocketEngine {
protected SSLEngine sslEngine = null;
// 四个buffer缓冲区
// private ByteBuffer myNetData;
// private ByteBuffer myAppData;
//// private ByteBuffer peerNetData;
// private ByteBuffer peerAppData;
private static final ByteBuffer dummy = ByteBuffer.allocate(0);
private static final int MAX_LOOP_IN_HANDSHAKE = 1000;
private boolean finished = false;
private boolean isFirstPacket = true;
protected SSLSocketEngine() {
}
public boolean isHandshakeFinish() {
return finished;
}
public ByteBuffer decrypt(ByteBuffer buff) throws SSLException {
ByteBuffer quickBuff = ByteBufferPool.malloc64K();
try {
SSLEngineResult result = sslEngine.unwrap(buff, quickBuff);// 调用SSLEngine进行unwrap操作
Status status = result.getStatus();
if(status != Status.OK) {
throw new SSLException("SSL unwrap error: "+status);
}
quickBuff.flip();
ByteBuffer newBuff = ByteBuffer.allocate(quickBuff.limit());
newBuff.put(quickBuff);
newBuff.rewind();
return newBuff;
} finally {
ByteBufferPool.free(quickBuff);
}
}
public ByteBuffer encrypt(ByteBuffer buff) throws SSLException {
ByteBuffer quickBuff = ByteBufferPool.malloc64K();
try {
SSLEngineResult result = sslEngine.wrap(buff, quickBuff);// 调用SSLEngine进行unwrap操作
Status status = result.getStatus();
if(status != Status.OK) {
throw new SSLException("SSL wrap error: "+status);
}
quickBuff.flip();
ByteBuffer newBuff = ByteBuffer.allocate(quickBuff.limit());
newBuff.put(quickBuff);
newBuff.rewind();
return newBuff;
} finally {
ByteBufferPool.free(quickBuff);
}
}
public boolean isFirstPacket() {
return isFirstPacket;
}
// 这个方法就是服务器端的握手
public void doHandshake(SSLChannel channel, ByteBuffer peerNetData, ByteBuffer peerAppData) throws IOException {
if(isFirstPacket) {
isFirstPacket = false;
sslEngine.beginHandshake();// 开始begin握手
}
System.out.println("receive size: "+peerNetData.remaining()+", channel: "+channel);
SSLEngineResult result;
Status status = null;// SSLEngineResult.Status
//握手阶段
HandshakeStatus hsStatus = sslEngine.getHandshakeStatus();
int loop = 0;
for(; loop