Saturday, April 28, 2012

Closing an SSLEngine Connection


This tip shows you how to correctly close a SSLEngine connection. Notice that this is not a simple process, like closing a simple socket! 

SSLContext context ...;
SSLEngine engine ...;
ByteBuffer dummy ...;
ByteBuffer OutputNet ...;

engine.closeOutbound();
while(!engine.isOutboundDone())
       {
       dummy.flip();
       OutputNet.clear();
       
       result=engine.wrap(dummy,OutputNet);
       status=result.getStatus();
       System.out.println("Status:"+status);
                                   
       if(status==SSLEngineResult.Status.BUFFER_OVERFLOW)
            {
            System.out.println("BUFFER_OVERFLOW");                   
            OutputNet=ByteBuffer.allocate(SOutputNet.capacity()+100);
            }
      
       if(status==SSLEngineResult.Status.OK)
            {                                    
            System.out.println("OK");
            while(OutputNet.hasRemaining())
                  {
                  try{
                     int W=channel.write(OutputNet);
                     if(W==-1)
                        {
                        //the channel has been closed
                        }                        
                     if(W==0)
                        {
                        //nothing has been read
                        }    
                     }catch(IOException e)
                        {
                        ?
                        }  
                   }
           OutputNet.compact();
           }        
           //BUFFER_UNDERFLOW, CLOSE                                               
        }   
//closing the transport mechanism
channel.close();                                                                     

No comments:

Post a Comment