我正在关注这个关于使用 .NET 进行数字签名/验证数据的精彩教程。我修改了该示例代码以使用 SHA256 并遇到“指定的算法无效”异常,这让我想到了这个关于在 .NET 4.0 中使用 SHA256 对数据进行签名的问题。
该帖子中的一个答案帮助我弄清楚如何通过显式加载支持 SHA256 的加密提供程序而不依赖可导出的私钥来正确生成数字签名(请参阅以下方法底部的代码,其中构造了RSACryptoServiceProvider ):
static string mKeyContainerName;
static byte[] SignText(string text, string publicCertPath)
{
// Access Personal (MY) certificate store of current user
X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
// Load the certificate we'll use to verify the signature from a file.
X509Certificate2 publicCert = new X509Certificate2(publicCertPath);
publicCert.Verify();
string publicHash = publicCert.GetCertHashString();
// Find the certificate we'll use …Run Code Online (Sandbox Code Playgroud)