python-3.x - 如何使用驻留在具有不可导出私钥的智能卡上的证书创建 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)
解决方案
推荐阅读
- node.js - nodejs自动维护winston日志
- windows - 我想用 Vagrant 在 OSX 上运行一个基本的 Windows 来宾,但我不断收到身份验证失败
- swift - 从初始化程序返回而不初始化所有存储的属性Swift Xcode 10.0
- sql - 使用别名或同义词的 SQL Server 跨数据库查询
- sql-server - 在同一查询中为 Oracle 和 SQL Server 转义特殊字符
- php - laravel 5.6 socialite auth by facebook email 为空
- android - 获取 Widevine 许可证服务器密钥
- image-processing - 对角线方向边缘检测
- symfony - 动态类加载 - 尝试从命名空间 _NAMESPACE_ 加载类 _CLASS_
- php - 使用没有错误消息的私人频道时无法从推送者那里获得响应