当前位置:   article > 正文

pythonssl双向认证_tls 双向认证 client端代码例子

python 使用pem证书 完成tls验证

1 importhttplib2 importjson3 importssl4 importurllib25 importrequests6

7

8 CA_FILE = "etc/rdtagent/cert/server/ca.pem"

9 CLIENT_CERT_FILE = "etc/rdtagent/cert/client/cert.pem"

10 CLIENT_KEY_FILE = "etc/rdtagent/cert/client/key.pem" #This is your client cert!

11 HOST = "127.0.0.1"

12 PORT = 8443

13

14 CACHE_URL = "/v1/cache"

15

16 context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH, cafile=CA_FILE)17 context.load_cert_chain(certfile=CLIENT_CERT_FILE, keyfile=CLIENT_KEY_FILE)18

19 connection = httplib.HTTPSConnection(HOST, port=PORT, context=context)20 #pem code

21 #auth_header = 'Basic %s' % (":".join(["myusername","mypassword"]).encode('Base64').strip('\r\n'))

22 #connection.request("POST", "/","",{'Authorization':auth_header})

23 connection.request('GET', CACHE_URL)24 response =connection.getresponse()25 print(response.status, response.reason)26

27 data =response.read()28 print(json.loads(data))29

30 connection.close()31

32

33

34 #http://docs.python-requests.org/en/latest/

35 res = requests.get("https://"+HOST+":"+str(PORT)+CACHE_URL, verify=CA_FILE, cert=(CLIENT_CERT_FILE, CLIENT_KEY_FILE), auth=('user', 'pass'))36 printres.json()37

38

39 #HTTPS Client Auth solution for urllib2, inspired by

40 #http://bugs.python.org/issue3466

41 #and improved by David Norton of Three Pillar Software. In this

42 #implementation, we use properties passed in rather than static module

43 #fields.

44 classHTTPSClientAuthHandler(urllib2.HTTPSHandler):45 def __init__(self, ca, key, cert):46 urllib2.HTTPSHandler.__init__(self)47 self.ca =ca48 self.key =key49 self.cert =cert50 defhttps_open(self, req):51 #Rather than pass in a reference to a connection class, we pass in

52 #a reference to a function which, for all intents and purposes,

53 #will behave as a constructor

54 returnself.do_open(self.getConnection, req)55 defgetConnection(self, host):56 print "*" * 80

57 printhost58 context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH, cafile=self.ca)59 context.load_cert_chain(certfile=self.cert, keyfile=self.key)60 return httplib.HTTPSConnection(host, key_file=self.key, cert_file=self.cert, context=context)61

62

63 #cert_handler = HTTPSClientAuthHandler(CA_FILE, CLIENT_KEY_FILE, CLIENT_CERT_FILE)

64 #opener = urllib2.build_opener(cert_handler)

65 #urllib2.install_opener(opener)

66

67 #https://docs.python.org/2/library/urllib2.html#examples

68 f = urllib2.urlopen("https://"+HOST+":"+str(PORT)+CACHE_URL, context=context)69 print json.loads(f.read())

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/59792
推荐阅读
相关标签
  

闽ICP备14008679号