2012-06-14 68 views
0

我有一個python服務器,需要一個客戶端使用證書進行身份驗證,我如何使客戶端腳本使用客戶端證書由服務器在python中使用ssl和套接字模塊進行身份驗證。python客戶端身份驗證使用ssl和套接字

是否有這種使用套接字和ssl只有出了扭曲的例子?

from OpenSSL import SSL 
from twisted.internet import ssl, reactor 
from twisted.internet.protocol import ClientFactory, Protocol 

class EchoClient(Protocol): 
    def connectionMade(self): 
    "print connected" 

    def dataReceived(self, data): 
     print "Server said:", data 
     self.transport.loseConnection() 

class EchoClientFactory(ClientFactory): 
    protocol = EchoClient 

    def clientConnectionFailed(self, connector, reason): 
     print "Connection failed - goodbye!" 
     reactor.stop() 

    def clientConnectionLost(self, connector, reason): 
     print "Connection lost - goodbye!" 
     reactor.stop() 

class CtxFactory(ssl.ClientContextFactory): 
    def getContext(self): 
     self.method = SSL.TLSv1_METHOD 
     ctx = ssl.ClientContextFactory.getContext(self) 
     ctx.use_certificate_file('client.crt') 
     ctx.use_privatekey_file('client.key') 
     return ctx 

if __name__ == '__main__': 

    factory = EchoClientFactory() 
    reactor.connectSSL('localhost', 8080, factory, CtxFactory()) 
    reactor.run() 
+0

謝謝你,我已經解決了吧:) –

回答

1
import socket, ssl, pprint 

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 

# require a certificate from the server 
ssl_sock = ssl.wrap_socket(s, 
       keyfile="client.key", 
       certfile="client.crt", 
       ca_certs="ca.crt", 
       cert_reqs=ssl.CERT_REQUIRED) 

ssl_sock.connect(('127.0.0.1', 8080)) 

print repr(ssl_sock.getpeername()) 
print ssl_sock.cipher() 
print pprint.pformat(ssl_sock.getpeercert()) 

ssl_sock.write("testing") 
data = ssl_sock.read() 
print data 

ssl_sock.close() 
相關問題