【问题标题】:Can you pass a digital certificate as a parameter, use it to sign, and not store it locally?能不能把一个数字证书作为参数传递,用它来签名,而不是存储在本地?
【发布时间】:2025-11-25 15:25:02
【问题描述】:

我已经搜索过了,但还没有找到答案。

如果我想使用数字证书签署某些东西,我通常必须将它放在我的证书存储中。

但是,是否可以将数字证书作为方法参数传递,使用证书对文档进行签名,而不以任何方式将其存储在本地?

我会在 C++ 或 C# 中执行此操作。

【问题讨论】:

  • 使用 CryptoAPI,这是通过创建内存存储来完成的(不确定 .NET Framework 是否允许这样做,或者您需要使用 P/Invoke)。或者您可以使用第三方库,例如 BouncyCastle 或我们的 SecureBlackbox 来完成这项工作(尤其是在您需要一些高级签名时)。

标签: c# visual-c++ digital-signature digital-certificate


【解决方案1】:

您可以使用X509Certificate2 类的各种构造函数从文件或字节数组创建证书。例如:

string certFile = @"MyCert.pfx";
string pfxPassword = "password"; // never hard code password in code

X509Certificate2 certificate = new X509Certificate2(certFile, pfxPassword, 
    X509KeyStorageFlags.MachineKeySet);
RSACryptoServiceProvider rsaCsp = (RSACryptoServiceProvider)certificate.PrivateKey;

然后您可以使用加密服务提供商进行签名,如How to: Sign XML Documents with Digital Signatures

现在“不以任何方式将其存储在本地”吗?好吧,不完全是。证书存储,但私钥存储在 Microsoft Cryptographic API Cryptographic Service Provider 密钥数据库中。

【讨论】: