gpt4 book ai didi

python - HSM 使用 PKCS11 中关键对象的标签

转载 作者:行者123 更新时间:2023-11-28 17:24:29 26 4
gpt4 key购买 nike

此代码块正在加载 cryptoki.so 库并检索插槽信息。这是获取插槽编号中的对象列表。 0. 我不需要访问所有的键来执行一些功能,只需要一个特定的键对。有没有办法通过使用标签名称、对象 ID 或句柄来获取单个所需的 token ?

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 或 --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 包含一个私有(private)/证书文件。我想指定这个特定的句柄。实际标签类似于 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" 或通过 handle $./Test.py --pin=pass --sign --handle=5313

已更新 来自以下建议的评论。仍然无法获取 rsa 私钥和证书的属性。使用特定 token 有效,但其中的那些对象返回错误的属性类型

   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 ====================

最佳答案

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

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

关于python - HSM 使用 PKCS11 中关键对象的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39920023/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com