PyKCS11获得令牌证书

时间:2016-09-06 10:20:08

标签: python openssl ssl-certificate pkcs#11

我正在使用PyKCS11库来读取令牌设备中的证书。

这是我现在使用的代码,问题是属性是二进制的。

pkcs11 = PyKCS11Lib()
pkcs11.load("C:\Windows\System32\eTPKCS11.dll")
slot = pkcs11.getSlotList()[2]
session = pkcs11.openSession(slot, PyKCS11.CKF_SERIAL_SESSION)
objects = session.findObjects([(PyKCS11.CKA_CLASS, PyKCS11.CKO_CERTIFICATE)])
all_attributes = [PyKCS11.CKA_SUBJECT, PyKCS11.CKA_VALUE, PyKCS11.CKA_ISSUER, PyKCS11.CKA_CERTIFICATE_CATEGORY, PyKCS11.CKA_END_DATE]

for object in objects:
    try:
        attributes = session.getAttributeValue(object, all_attributes)
    except PyKCS11.PyKCS11Error as e:
        continue

    attrDict = dict(list(zip(all_attributes, attributes)))

    if attrDict[PyKCS11.CKA_CERTIFICATE_CATEGORY] == (0x2, 0x0, 0x0, 0x0):
        continue

    print attrDict[PyKCS11.CKA_SUBJECT]
    print attrDict[PyKCS11.CKA_VALUE]

session.closeSession()

它打印的是一个元组,如:(48L,130L,5L,192L,48L,130L,4L,168L)。

如何提取主题名称和x509证书?4

修改

我最终设法解决了这个问题。以防万一其他人在努力获取证书:

    pkcs11 = PyKCS11Lib()
    pkcs11.load("C:\Windows\System32\eTPKCS11.dll")
    slot = pkcs11.getSlotList()[2]
    session = pkcs11.openSession(slot, PyKCS11.CKF_SERIAL_SESSION)
    objects = session.findObjects([(PyKCS11.CKA_CLASS, PyKCS11.CKO_CERTIFICATE)])
    all_attributes = [PyKCS11.CKA_SUBJECT, PyKCS11.CKA_VALUE, PyKCS11.CKA_ISSUER, PyKCS11.CKA_CERTIFICATE_CATEGORY, PyKCS11.CKA_END_DATE]

    for object in objects:
        try:
            attributes = session.getAttributeValue(object, all_attributes)
        except PyKCS11.PyKCS11Error as e:
            continue

        attrDict = dict(list(zip(all_attributes, attributes)))

        if attrDict[PyKCS11.CKA_CERTIFICATE_CATEGORY] == (0x2, 0x0, 0x0, 0x0):
            continue

        x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_ASN1,
                                                   str(bytearray(attrDict[PyKCS11.CKA_VALUE])))

    session.closeSession()

0 个答案:

没有答案