用于签署散列和验证散列签名的 MSDN C 示例程序不起作用

MSDN C example program for signing a hash and verifying the hash signature doesn't work

我已经在 MSDN 上试用了示例程序,它演示了如何对散列进行签名和验证散列签名。但是当我执行程序时,我得到以下输出:

CSP context acquired.
An error occurred in running the program.
Error during CryptGetUserKey for signkey.
Error number 8009000d.
Program terminating.

8009000d 是 NTE_NO_KEY 的数字错误代码。有谁知道为什么程序会以这种方式失败?我在 Windows 7.

显然您获取的上下文中没有密钥。

您可以稍微更改此示例,将其与另一个有关上下文获取和密钥生成的 Microsoft 示例结合使用。如果缺少这些,您只需添加用于生成密钥的代码:

...
if (CryptGetUserKey(hProv,  AT_SIGNATURE, &hKey)) {  // if block unchanged
    printf("The signature key has been acquired. \n");
}
else if (GetLastError() == NTE_NO_KEY) {             // insert processing of missing keys 
    if (CryptGenKey(                                
        hProv,
        AT_SIGNATURE,
        0,
        &hKey)) {
        printf("Created a signature key pair.\n");
    }
    else {
        MyHandleError("Error during creation of new signature key.");
    }
}
else {                      // The original else part will handle other errors
    MyHandleError("Error during CryptGetUserKey for signkey.");
}