使用智能卡证书和公钥进行网站身份验证



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

现在我必须用python编写一个程序,它可以读取卡并登录该网站。在互联网上研究后,我发现我需要提取:

  1. 证书和
  2. 公钥(因为无法提取私钥(

,然后使用这两件事创建HTTPs连接(这里的示例(。到目前为止,我能够提取pem格式的证书。但到目前为止,我还找不到以pem格式提取密钥的方法。我用PyKCS11读卡片。以下是我的代码:

from asn1crypto import pem, x509
from PyKCS11 import *
import binascii
pkcs11 = PyKCS11Lib()
pkcs11.load(r'C:WindowsSystem32XXXX.dll')
print(pkcs11.getSlotList(tokenPresent=False))
slot = pkcs11.getSlotList(tokenPresent=False)[0]
print(pkcs11.getTokenInfo(slot))
session = pkcs11.openSession(0, CKF_SERIAL_SESSION | CKF_RW_SESSION)
session.login('123456')
result = []
result_pem = []

# find public key and print modulus
pubKey = session.findObjects([(CKA_CLASS, CKO_PUBLIC_KEY)])[0]
modulus = session.getAttributeValue(pubKey, [CKA_MODULUS])[0]
print("nmodulus: {}".format(binascii.hexlify(bytearray(modulus))))
#find certificates
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)
print(result)

以下是我的问题:1.我的做法正确吗?

  1. 如果是,那么如何提取pem格式的公钥?

  2. 这种智能卡身份验证实际上是如何在客户端和服务器端工作的?

公钥互斥

如果你已经导出了证书,那么从那里提取公钥可能比从智能卡提取公钥更容易。您可以为此使用openssl:

openssl x509 -in cert.pem -pubkey -out pubkey.pem -noout

身份验证

您试图实现的是使用客户端证书打开具有相互身份验证的TLS连接。如果这样做,客户端证书的私钥会对握手的部分进行签名,以向服务器进行身份验证。

从智能卡中提取证书和公钥对您没有帮助。你需要找到一个库,它允许你直接使用PKCS#11令牌中的私钥。

最新更新