PyKCS11 get token certificates

浪子不回头ぞ 提交于 2021-01-01 03:59:54

问题


I am using PyKCS11 library to read read the certificates from a token device.

This is the code I am using right now, the problem is that the attributes are binary.

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()

What it prints is a tuple, something like: (48L, 130L, 5L, 192L, 48L, 130L, 4L, 168L).

How can I extract the subject name and the x509 certificate ?4

EDIT

I managed to solve it in the end. Just in case someone else is struggling this is the way to to get the certificate:

    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()

来源:https://stackoverflow.com/questions/39346577/pykcs11-get-token-certificates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!