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

时间:2016-10-07 14:45:57

标签: python encryption cryptography pkcs#11 hsm

这段代码正在加载cryptoki.so库并检索插槽信息。这是获得插槽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并获取以下内容

Library manufacturerID: Safenet, Inc.                   
Available Slots: 4
Slot no: 0
  slotDescription: ProtectServer K5E:00045
  manufacturerID: SafeNet Inc.
TokenInfo
  label: CKM
  manufacturerID: SafeNet Inc.
  model: K5E:PL25
Opened session 0x00000002

Found 52 objects: [5021, 5022, 5014, 5016, 4, 5, 6, 7, 8, 9, 16, 18, 23, 24, 26, 27, 29, 30, 32, 33, 35, 36, 38, 39, 5313, 5314, 4982, 5325, 5326, 5328, 5329, 5331, 5332, 5335, 5018, 4962, 5020, 4963, 5357, 5358, 5360, 5361, 5363, 5364, 5366, 5367, 5369, 5370, 5372, 5373, 5375, 5376]

我最终只想让其中一个对象运行一些测试。例如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 ====================

1 个答案:

答案 0 :(得分:1)

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

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

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

# get objects labelled "PRIV"
objects = session.findObjects([(CKA_LABEL, "PRIV")])

# get all private key objects
objects = session.findObjects([(CKA_CLASS, CKO_PRIVATE_KEY)])

# get all private key objects labelled "PRIV"
objects = session.findObjects([(CKA_CLASS, CKO_PRIVATE_KEY),(CKA_LABEL, "PRIV")])

# get all RSA private key objects labelled "PRIV"
objects = session.findObjects([(CKA_CLASS, CKO_PRIVATE_KEY),(CKA_KEY_TYPE, CKK_RSA),(CKA_LABEL, "PRIV")])

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

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

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

Soma附加(随机)笔记:

  • 不依赖句柄 - 他们可能(并且会)因不同的程序运行而不同

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

免责声明:我不是那样进入python所以请确认我的想法

祝你好运!

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

没有错误(最有可能)显示,因为异常被捕获并被忽略:

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