我遇到了类似的问题,除了我在 Windows 上并且需要使用“capi”引擎来处理智能卡客户端证书。我有一个使用 cffi 的工作代码和使用 pyopenssl 的请求,我希望更改它以支持 pkcs11 应该不会太困难。
import os
import ssl
import sys
import cffi
import requests
pyopenssl = requests.packages.urllib3.contrib.pyopenssl
pyopenssl.inject_into_urllib3()
# I use anaconda and these paths are valid for me, change as required
libcryptopath = os.path.join(sys.prefix, "Library", "bin", "libcrypto-1_1-x64.dll")
libsslpath = os.path.join(sys.prefix, "Library", "bin", "libssl-1_1-x64.dll")
capipath = os.path.join(sys.prefix, "Library", "lib", "engines-1_1", "capi.dll")
ffi = cffi.FFI()
ffi.cdef(
"void *ENGINE_by_id(const char *id);"
"int ENGINE_ctrl_cmd_string(void *e, const char *cmd_name, const char *arg, int cmd_optional);"
"int ENGINE_init(void *e);"
"int SSL_CTX_set_client_cert_engine(void *ctx, void *e);"
)
try:
libcrypto, libssl, engine
except NameError:
libcrypto = ffi.dlopen(libcryptopath)
libssl = ffi.dlopen(libsslpath)
engine = libcrypto.ENGINE_by_id(b"dynamic")
libcrypto.ENGINE_ctrl_cmd_string(engine, b"SO_PATH", capipath.encode(), 0)
libcrypto.ENGINE_ctrl_cmd_string(engine, b"LOAD", ffi.NULL, 0)
libcrypto.ENGINE_init(engine)
class PyOpenSSLContextCAPI(pyopenssl.PyOpenSSLContext):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
libssl.SSL_CTX_set_client_cert_engine(self._ctx._context, engine)
# https://lukasa.co.uk/2017/02/Configuring_TLS_With_Requests/
class HTTPAdapterCAPI(requests.adapters.HTTPAdapter):
def init_poolmanager(self, *args, **kwargs):
context = PyOpenSSLContextCAPI(ssl.PROTOCOL_TLS)
kwargs['ssl_context'] = context
return super().init_poolmanager(*args, **kwargs)
class SessionCAPI(requests.Session):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.mount("https://", HTTPAdapterCAPI())
if __name__ == '__main__':
s = SessionCAPI()
r = s.get("https://example.com")
print(r.text)