C_GenerateKeyPair 返回 CKR_USER_NOT_LOGGED_IN

C_GenerateKeyPair returned CKR_USER_NOT_LOGGED_IN

using (Session session = slot.OpenSession(SessionType.ReadWrite))
{
    session.Login(CKU.CKU_SO, "pin");                   

    List<ObjectAttribute> publicKeyAttributes = new List<ObjectAttribute>();
    publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_SECRET_KEY));
    publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_RSA));
    publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_CERTIFICATE));
    publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_PRIVATE_KEY));
    publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_LABEL, "label2"));
    publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_LABEL, "label1"));
    publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_LABEL, "Pkcs11Interop"));

    List<ObjectHandle> foundPublicKeys = session.FindAllObjects(publicKeyAttributes);
}

我正在尝试使用 Pkcs11Interop 库从 HSM 获取我自己的证书并从账单中获取它。

当我尝试使用此代码查找我自己的证书时:

var foundObjects = session.FindAllObjects (searchTemplate)

返回零 (0)。

session.GenerateKeyPair (mechanism, publicKeyAttributes, privateKeyAttributes, out publicKeyHandle, out privateKeyHandle);

我找到了这段代码,但出现错误。

C_GenerateKeyPair returned CKR_USER_NOT_LOGGED_IN 

谁能帮帮我?谢谢。

所以让我们回答我猜你想问的问题:

Question #1: When I try to find my own certificate object with var foundObjects = session.FindAllObjects(searchTemplate); I get zero objects. Why?

您没有 post 您的搜索模板,所以我只能猜测。我的猜测是您的搜索模板与您期望找到的对象的属性不匹配。换句话说,您的令牌上没有符合搜索模板条件的对象。

有关详细信息,请参阅 PKCS#11 v2.20 specificationC_FindObjectsInit 函数的文档。它指出:

The matching criterion is an exact byte-for-byte match with all attributes in the template.

您还可以阅读 PKCS#11 v2.20 specification 的第 10 章以熟悉 PKCS#11 对象类型及其属性。

Question #2: When I try to generate new key pair with session.GenerateKeyPair() method I get error C_GenerateKeyPair returned CKR_USER_NOT_LOGGED_IN. Why?

PKCS#11 v2.20 specification 的第 6.5 章指出:

Only the normal user is allowed access to private objects on the token, and that access is granted only after the normal user has been authenticated. Some tokens may also require that a user be authenticated before any cryptographic function can be performed on the token, whether or not it involves private objects.

所以我想您必须首先通过调用 session.Login() 方法对您的令牌进行身份验证,然后您应该能够创建新的令牌对象(生成密钥)。


请注意,强烈建议 在开始使用 Pkcs11Interop 之前,您至少要熟悉 "Chapter 2 - Scope"PKCS#11 v2.20 specificiation"Chapter 6 - General overview""Chapter 10 - Objects"(或任何先前或后续规范版本的等效章节)。