在PKCS11中使用密钥对象标签的HSM

2024-10-05 12:17:24 发布

您现在位置:Python中文网/ 问答频道 /正文

此代码块正在加载克洛特基。所以库和检索插槽信息。这是在slot num.0中获取一个对象列表。我不需要访问所有的密钥来执行一些功能,只需要访问特定的密钥对。有没有一种方法可以通过使用标签名、对象ID或句柄来获得一个所需的令牌?在

pkcs11 = PyKCS11.PyKCS11Lib()
pkcs11.load(lib)
pkcs11.initialize()
info = pkcs11.getInfo()
i = pkcs11.getSlotInfo(0)
pkcs11.openSession(0)

print "Library manufacturerID: " + info.manufacturerID

slots = pkcs11.getSlotList()
print "Available Slots:", len(slots)

for s in slots:
try:
    i = pkcs11.getSlotInfo(s)
    print "Slot no:", s
    print format_normal % ("slotDescription", i.slotDescription.strip())
    print format_normal % ("manufacturerID", i.manufacturerID.strip())

    t = pkcs11.getTokenInfo(s)
    print "TokenInfo"
    print format_normal % ("label", t.label.strip())
    print format_normal % ("manufacturerID", t.manufacturerID.strip())
    print format_normal % ("model", t.model.strip())


    session = pkcs11.openSession(s)
    print "Opened session 0x%08X" % session.session.value()
    if pin_available:
        try:
            session.login(pin=pin)
        except:
            print "login failed, exception:", str(sys.exc_info()[1])

    objects = session.findObjects()
    print
    print "Found %d objects: %s" % (len(objects), [x.value() for x in objects])

我正在运行的特定脚本只定义了几个命令,例如-pin --sign --decrypt --lib我是否需要定义一个通用的pkcs11-tool例如--init-token or --token-label来在执行脚本时将其作为参数传递?或者,我可以在python脚本中将变量直接分配给所需的LabelName吗?在

所以我从命令行运行

$./Test.py --pin=pass并得到以下结果

^{pr2}$

我最终只想让这些对象中的一个运行一些测试。用于实例objectID = 201603040001包含一个私有/cert文件。我想指定这个特殊的句柄。实际的标签类似于000103...3A0。我如何定义它,这样我就不会得到库中的其他对象了。在

下面是几个HSM对象的列表

 HANDLE LABEL                  TYPE                       OBJECT-ID
  5314 00000103000003A1       X509PublicKeyCertificate   201603040001
  5313 00000103000003A1       RSAPrivateKey              201603040001

我只想拉一个标签。在

下面是定义的用法

def usage():
    print "Usage:", sys.argv[0],
    print "[-p pin][--pin=pin]",
    print "[-s slot][--slot=slot]",
    print "[-c lib][--lib=lib]",
    print "[-h][--help]",
    print "[-o][--opensession]"

try:
    opts, args = getopt.getopt(sys.argv[1:], "p:c:Sd:h:s", ["pin=", "lib=", "sign", "decrypt", "help","slot="])
except getopt.GetoptError:
    # print help information and exit:
    usage()
    sys.exit(2)

我不知道如何添加一个参数,以便只使用一个特定的标签--sign。结束游戏我想用$./Test.py --pin=pass --sign --label "00000103000003A4"或按手柄$./Test.py --pin=pass --sign --handle=5313

根据下面的建议意见更新了。在获取rsa私钥和证书的属性时仍有问题。使用特定的令牌已经起作用,但其中的对象返回了错误的属性类型

   t = pkcs11.getTokenInfo(s)
    print "TokenInfo"
    if 'CKM' == t.label.decode('ascii').strip():
            tokenInfo = pkcs11.getTokenInfo(slot)
    if '00000103000003A1' == tokenInfo.label.decode('ascii').strip():
            print format_normal % ("label", t.label.strip())
            print format_normal % ("manufacturerID", t.manufacturerID.strip())
            print format_normal % ("model", t.model.strip())


            session = pkcs11.openSession(s)
    print("Opened session 0x%08X" % session.session.value())
    if pin_available:
        try:
            if (pin is None) and \
                    (PyKCS11.CKF_PROTECTED_AUTHENTICATION_PATH & t.flags):
                print("\nEnter your PIN for %s on the pinpad" % t.label.strip())
            session.login(pin=pin)
        except:
            print("login failed, exception:", str(sys.exc_info()[1]))
            break

    objects = session.findObjects([(CKA_LABEL, "00000103000003A4")])
    print()
    print("Found %d objects: %s" % (len(objects), [x.value() for x in objects]))

    all_attributes = list(PyKCS11.CKA.keys())
    # only use the integer values and not the strings like 'CKM_RSA_PKCS'
    all_attributes.remove(PyKCS11.CKA_PRIVATE_EXPONENT)
    all_attributes.remove(PyKCS11.CKA_PRIME_1)
    all_attributes.remove(PyKCS11.CKA_PRIME_2)
    all_attributes.remove(PyKCS11.CKA_EXPONENT_1)
    all_attributes.remove(PyKCS11.CKA_EXPONENT_2)
    all_attributes.remove(PyKCS11.CKA_COEFFICIENT)
    all_attributes = [e for e in all_attributes if isinstance(e, int)]

          n_obj = 1
    for o in objects:
        print()
        print((red + "==================== Object: %d ====================" + normal) % o.value())
        n_obj += 1
        try:
            attributes = session.getAttributeValue(o, all_attributes)
        except PyKCS11.PyKCS11Error as e:
            continue    
        attrDict = dict(zip(all_attributes, attributes))
        if attrDict[PyKCS11.CKA_CLASS] == PyKCS11.CKO_PRIVATE_KEY \
           and attrDict[PyKCS11.CKA_KEY_TYPE] == PyKCS11.CKK_RSA:
            m = attrDict[PyKCS11.CKA_MODULUS]
            e = attrDict[PyKCS11.CKA_PUBLIC_EXPONENT]
            if m and e:
                mx = eval(b'0x' + ''.join("%02X" %c for c in m))
                ex = eval(b'0x' + ''.join("%02X" %c for c in e))
            if sign:
                try:
                    toSign = "12345678901234567890123456789012"  # 32 bytes, SHA256 digest
                    print("* Signing with object 0x%08X following data: %s" % (o.value(), toSign))
                    signature = session.sign(o, toSign)
                    sx = eval(b'0x' + ''.join("%02X" % c for c in signature))
                    print("Signature:")
                    print(dump(''.join(map(chr, signature))))
                    if m and e:
                        print("Verifying using following public key:")
                        print("Modulus:")
                        print(dump(''.join(map(chr, m))))
                        print("Exponent:")
                        print(dump(''.join(map(chr, e))))
                        decrypted = pow(sx, ex, mx)  # RSA
                        print("Decrypted:")
                        d = binascii.unhexlify(hexx(decrypted))
                        print(dump(d))
                        if toSign == d[-20:]:
                            print("*** signature VERIFIED!\n")

下面是打印的内容。使用特定对象似乎没有任何工作,没有错误消息

Slot no: 0
  slotDescription: ProtectServer K5E:00045
  manufacturerID: SafeNet Inc.
TokenInfo
Opened session 0x00000002

Found 2 objects: [5328, 5329]

==================== Object: 5328 ====================

==================== Object: 5329 ====================

Tags: forifobjectssessionpinalllabelattributes
1条回答
网友
1楼 · 发布于 2024-10-05 12:17:24

您只能使用一个令牌,方法是在使用前检查其标签,例如:

tokenInfo = pkcs11.getTokenInfo(slot)
if 'DesiredTokenLabel' == tokenInfo.label.decode('ascii').strip():
    # Start working with this particular token
    session = pkcs11.openSession(s)

您可以使用findObjects调用的模板参数仅枚举特定对象,例如:

^{pr2}$

下面是带有硬编码参数的示例代码:

from PyKCS11 import *

pkcs11 = PyKCS11.PyKCS11Lib()
pkcs11.load("your module path...")
slots = pkcs11.getSlotList()
for s in slots:
    t = pkcs11.getTokenInfo(s)
    if 'CKM' == t.label.decode('ascii').strip():
        session = pkcs11.openSession(s)
        objects = session.findObjects([(CKA_LABEL, "00000103000003A1")])
        print ("Found %d objects: %s" % (len(objects), [x.value() for x in objects]))

请注意,它是python3,因为我现在不能在python2.x中使用PyKCS11。在

Soma附加(随机)注释:

  • 不要依赖句柄,因为不同的程序运行,它们可能(并且将)不同

  • 程序的命令行参数由您决定您的程序是否需要 token-label

免责声明:我不喜欢python,所以请验证我的想法

祝你好运!在

编辑(关于您最近的编辑)>

由于捕获并忽略异常,因此(很可能)不会显示错误:

try:
    attributes = session.getAttributeValue(o, all_attributes)
except PyKCS11.PyKCS11Error as e:
    continue

相关问题 更多 >

    热门问题