如何验证在Python SSL证书
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何验证在Python SSL证书相关的知识,希望对你有一定的参考价值。
参考技术A import osimport glob
from OpenSSL.SSL import Context, TLSv1_METHOD, VERIFY_PEER, VERIFY_FAIL_IF_NO_PEER_CERT, OP_NO_SSLv2
from OpenSSL.crypto import load_certificate, FILETYPE_PEM
from twisted.python.urlpath import URLPath
from twisted.internet.ssl import ContextFactory
from twisted.internet import reactor
from twisted.web.client import getPage
certificateAuthorityMap =
for certFileName in glob.glob("/etc/ssl/certs/*.pem"):
# There might be some dead symlinks in there, so let's make sure it's real.
if os.path.exists(certFileName):
data = open(certFileName).read()
x509 = load_certificate(FILETYPE_PEM, data)
digest = x509.digest('sha1')
# Now, de-duplicate in case the same cert has multiple names.
certificateAuthorityMap[digest] = x509
class HTTPSVerifyingContextFactory(ContextFactory):
def __init__(self, hostname):
self.hostname = hostname
isClient = True
def getContext(self):
ctx = Context(TLSv1_METHOD)
store = ctx.get_cert_store()
for value in certificateAuthorityMap.values():
store.add_cert(value)
ctx.set_verify(VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT, self.verifyHostname)
ctx.set_options(OP_NO_SSLv2)
return ctx
def verifyHostname(self, connection, x509, errno, depth, preverifyOK):
if preverifyOK:
if self.hostname != x509.get_subject().commonName:
return False
return preverifyOK
def secureGet(url):
return getPage(url, HTTPSVerifyingContextFactory(URLPath.fromString(url).netloc))
def done(result):
print 'Done!', len(result)
secureGet("https://google.com/").addCallback(done)
reactor.run()
这个验证要安装 Twisted 库。
当然这样的库好多,如:pycurl,requests,M2Crypto
import requestsrequests.get('https://somesite.com', cert='/path/server.crt', verify=True)本回答被提问者采纳
Python-requests的使用 - SSL证书验证
一、SSL问题
1、在你不启用fiddler时,python代码直接发送https请求,不会有SSL问题(也就是说不想看到SSL问题,关掉fiddler就行)
2.启用fiddler会报出以下错误:
raise SSLError(e, request=request)
requests.exceptions.SSLError: HTTPSConnectionPool(host=\'163.com\', port=443): Max retries exceeded with url: / (Caused by SSLError(SSLCertVerificationError(1, \'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)\')))
verify参数设置
1、Requests的请求默认verify=True
2、如果你将 verify设置为 False,Requests 也能忽略对 SSL 证书的验证
3、但是依然会出现两行Warning,可以不用管
Python3 提示warning 添加如下三种任意一种代码即可解决:
方式1:
import requests requests.packages.urllib3.disable_warnings
方式2:
import warnings warnings.filterwarnings("ignore")
方式3:
import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
以上是关于如何验证在Python SSL证书的主要内容,如果未能解决你的问题,请参考以下文章
Python - [SSL: CERTIFICATE_VERIFY_FAILED] 证书验证失败:无法获取本地颁发者证书 (_ssl.c:1091)