使用ssl和socket进行python客户端身份验证 [英] python client authentication using ssl and socket

查看:855
本文介绍了使用ssl和socket进行python客户端身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要客户端使用证书进行身份验证的python服务器,我如何制作一个客户端脚本,该脚本使用ssl和套接字模块在python中通过服务器对客户端证书进行身份验证.

i have a python server that needs a client to authenticate using certificates, how can i make a client script that uses client certificates to be authenticated by the server in python using ssl and socket modules.

是否有使用插座和ssl而不扭曲的示例?

is there example for this using socket and ssl only with out twisted?

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()

推荐答案

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()

这篇关于使用ssl和socket进行python客户端身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆