[英]How to read certificate from smart card via python?
I have a Smart Card (actually USB Token) with some certificate and keys written on it. 我有一个智能卡(实际上是USB令牌),上面写有一些证书和密钥。 Now I need to retrieve this certificate using python on Windows.
现在,我需要在Windows上使用python检索此证书。 How can it be achieved?
如何实现?
I had a look on pyscard
package but it seems too low-level and probably not a most simple way of doing this. 我看了
pyscard
软件包,但它似乎太底层了,可能不是最简单的方法。 But if you know that low-level answer then your help will be appreciated. 但是,如果您知道该低级答案,那么您的帮助将不胜感激。
Seems like CryptAcquireContext
function from pywin32 (win32crypt) allow me to use private key from smart card for encryption purposes but I cannot get the certificate itself. 似乎来自pywin32(win32crypt)的
CryptAcquireContext
函数允许我使用智能卡中的私钥进行加密,但是我无法获取证书本身。
Do you have any suggestions? 你有什么建议吗?
Found an answer myself though. 我自己找到了答案。 Hope it will help someone:
希望它能帮助某人:
Usually smart card manufacturers provide a library ( .so
or .dll
) implementing PKCS#11 standard. 通常,智能卡制造商提供实现PKCS#11标准的库(
.so
或.dll
)。
There are several solutions which you can use to communicate with your smart card via this library. 您可以使用多种解决方案通过此库与智能卡进行通信。 Such as: pkcs11-tool (CLI interface), PyKCS11 (python wrapper).
如: pkcs11-tool (CLI接口), PyKCS11 (python包装器)。
Here is an example how it could be achieved with PyKCS11: 这是一个使用PyKCS11如何实现的示例:
from asn1crypto import x509
from PyKCS11 import *
pkcs11 = PyKCS11Lib()
pkcs11.load('<MANUFACTURER_LIBRARY_PATH>')
# get slot value via pkcs11.getSlotList(tokenPresent=False). Usually it's 0
session = pkcs11.openSession(slot, CKF_SERIAL_SESSION | CKF_RW_SESSION)
session.login('<SMART_CARD_PIN_CODE>')
result = []
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)
result.append(cert)
print(result)
This way I was able to list certificates on smart card both on Linux and Windows 这样,我就可以在Linux和Windows上列出智能卡上的证书
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.