我尝试使用提供商提供的p12证书进行身份验证,并希望使用它来获取网站的html主体。
我目前有以下代码:
import contextlib
import OpenSSL.crypto
import os
import requests
import ssl
import tempfile
import http.client
import shutil
from OpenSSL import crypto
url = "https://website.com/"
p12_cert = "cert.p12"
password = "password"
@contextlib.contextmanager
def pfx_to_pem(pfx_path, pfx_password):
''' Decrypts the .pfx file to be used with requests. '''
with tempfile.NamedTemporaryFile(suffix='.pem') as t_pem:
f_pem = open(t_pem.name, 'wb')
pfx = open(pfx_path, 'rb').read()
p12 = OpenSSL.crypto.load_pkcs12(pfx, pfx_password)
f_pem.write(OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, p12.get_privatekey()))
f_pem.write(OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, p12.get_certificate()))
f_pem.close()
yield t_pem.name
with pfx_to_pem(p12_cert, password) as cert:
requests.get(url, verify=cert)
任何指导都非常适用。
由于
答案 0 :(得分:0)
您可以将p12文件拆分为证书/密钥部分,并将其用作元组,并以requests代替单个.pem文件路径。
完成操作后,别忘了删除密钥和crt文件,以防您不想永久存储未加密的p12文件,而只想在运行时对其进行解密。
certpw = 'myTopSecretPassword'
# create pem file from p12
p12 = crypto.load_pkcs12(open("/file.p12", 'rb').read(), certpw.encode())
# PEM formatted private key
k = crypto.dump_privatekey(crypto.FILETYPE_PEM, p12.get_privatekey())
fkey = open('/myKey.key', 'wb')
fkey.write(k)
fkey.close()
# PEM formatted certificate
c = crypto.dump_certificate(crypto.FILETYPE_PEM, p12.get_certificate())
fcert = open('/myCert.crt', 'wb')
fcert.write(c)
fcert.close()
clientcert = ('/myCert.crt', '/myKey.key')
# if you work with a .pem file, you simply use 'cert='/myPEMFile.pem' after dumping the key/cert data in the .pem file
requests.get('https://someurl.org', cert=('/myCert.crt', '/myKey.key'))