使用python中的客户端证书的相互认证

问题描述 投票:0回答:1

所以我有一张信用卡,看起来像带芯片的智能卡。将卡插入读卡器后,该卡将在网站上登录。

现在,我必须使用python编写程序,该程序可以读取卡并在该网站上登录。经过对Internet的研究,我发现我需要从卡中提取证书,然后使用它来创建HTTPS连接。到目前为止,我能够提取pem格式的证书。我使用PyKCS11提取证书。下面是我的代码:

from asn1crypto import pem, x509
from PyKCS11 import *
import binascii

pkcs11 = PyKCS11Lib()
pkcs11.load(r'C:\Windows\System32\XXXX.dll')
print(pkcs11.getSlotList(tokenPresent=False))
slot = pkcs11.getSlotList(tokenPresent=False)[0]
print(pkcs11.getTokenInfo(slot))
# get slot value via pkcs11.getSlotList(tokenPresent=False). Usually it's 0
session = pkcs11.openSession(0, CKF_SERIAL_SESSION | CKF_RW_SESSION)
session.login('123456')
result = []
result_pem = []



certs = session.findObjects([(CKA_CLASS, CKO_CERTIFICATE)])
for cert in certs:
    cka_value, cka_id = session.getAttributeValue(cert, [CKA_VALUE, CKA_ID])
    cert_der = bytes(cka_value)
    cert = x509.Certificate.load(cert_der)
    # Write out a PEM encoded value
    cert_pem = pem.armor('CERTIFICATE', cert_der)
    result.append(cert)
    result_pem.append(cert_pem)
    with open('cert.pem','wb') as f:
         f.write(cert_pem)

现在,我正在发送HTTPS请求,其中包含提取的卡的证书和卡的PIN。下面是我的代码:

import http.client
import json
import ssl

# Defining certificate related stuff and host of endpoint
certificate_file = r'C:\Users\XXXXX\Documents\Reporting Tool\cert.pem'
certificate_secret= '123456'
host = "example.com"

# Defining parts of the HTTP request
request_url='/login.form'

request_headers = {
        'user-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36'
    }

request_body_dict={
    'login-form-type': 'cert'
}

# Define the client certificate settings for https connection
context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
context.load_cert_chain(certfile=certificate_file, password=certificate_secret) ##gives error

此代码的最后一行抛出错误:

Exception has occurred: SSLError
[SSL] PEM lib (_ssl.c:3845)

所以这是我的问题:

  1. 我的方法正确吗?
  2. 如果是,那么如何解决此错误?
python python-3.x https certificate smartcard
1个回答
-2
投票

[enter image description here; lkjhgfdsdfrthnsbsrgbrfgbd df advdscsDC SC SDCDSCSA CS

© www.soinside.com 2019 - 2024. All rights reserved.