首页 > 解决方案 > 如何使用驻留在具有不可导出私钥的智能卡上的证书创建 SSL 上下文?

问题描述

我正在尝试使用请求库连接到需要提供客户端证书的服务器。我可以获得证书,但不能获得私钥。

我能够从智能卡中提取证书(使用加密库加载通过 pkcs11 访问的 x509 证书),并且能够以请求预期的 PEM 格式序列化这些证书。pkcs11 还提供对位于卡上的私钥的访问;我可以使用它们来执行诸如签名或解密之类的操作。但是,由于它们被标记为不可导出(这是有道理的,毕竟它们是私钥),因此我无法将它们序列化为文件以在创建 SSL 上下文时提供。

我已经看到用 Java 编写的这个问题的解决方案,其中访问卡上的密钥库/密钥管理器,并且密钥以这种方式与上下文相关联,但我还没有找到在 Python 中这样做的方法。

编辑:这是在 Windows 机器上完成的。我也尝试过使用 M2Crypto 库,但是我无法成功安装该库(即使使用 M2CryptoWin64 也是如此)。

import pkcs11
from pkcs11.constants import ObjectClass
from pkcs11.mechanisms import KeyType, Mechanism
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.serialization import Encoding

lib = pkcs11.lib("path/to/pkcs11/dll")
slots = lib.get_slots(token_present=True)
token = slots[0].get_token()
with token.open(rw=True, user_pin="1234") as session:
    attrs = {
        pkcs11.Attribute.CLASS: ObjectClass.CERTIFICATE
    }
    certs = tuple(session.get_objects(attrs))
    x509cert = x509.load_der_x509_certificate(certs[0][pkcs11.Attribute.VALUE], default_backend())
    with open("cert_file", 'wb') as certfile:
        certfile.write(x509cert.public_bytes(Encoding.PEM))

     r = requests.get("https://www.google.com",
         verify=False,
         cert="cert_file")
     print(r.text)

标签: python-3.xauthenticationsslsmartcard

解决方案


推荐阅读