请注意,我使用SHA512,但SHA256也可以在以下示例中使用:
"Invalid algorithm specified" 对我来说花费了很长时间才找到解决方案,我尝试过几乎所有可能的方法。
步骤1 - 证书必须是SHA512,并使用支持SHA512的CSP(加密服务提供程序)。以下是CSP及其功能列表。如果您寻找SHA512,您将找到“Microsoft Enhanced RSA and AES Cryptographic Provider”。默认情况下,在Windows中生成证书不会使用它,因此您必须在创建证书时指定它。
如果您使用openssl创建证书,您可以使用-CSP选项设置正确的CSP以使其正常工作。如果您有现成的pfx,则可以使用openssl将其转换为PEM文件,然后再转回pfx以添加该选项。
创建私钥和证书-此步骤将询问您问题,如州,地区等。
openssl req -x509 -nodes -sha512 -newkey rsa:2048 -keyout 512key.pem -out 512cert.pem -days 3650
使用Microsoft增强型RSA和AES加密提供程序创建PFX文件,以便导入到您的证书存储中:
openssl pkcs12 –export –in 512cert.pem –inkey 512key.pem –CSP “Microsoft Enhanced RSA and AES Cryptographic Provider” –out 512pfx.pfx
步骤2: 感谢Gonzalo Gallotti发布了帮助我的代码片段的链接。我对我的代码进行了注释以显示每个步骤的操作。注意:如步骤1所述,如果没有正确生成的证书,此代码将无法运行。
public void GetCertificate() {
var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
string alg = CryptoConfig.MapNameToOID("SHA512");
store.Open(OpenFlags.ReadWrite);
foreach (X509Certificate2 myCert in store.Certificates)
{
if (myCert.IssuerName.Name.Contains("CN=YourSite"))
{
if (myCert.HasPrivateKey)
{
string mySignature = GetSignatureString();
byte[] originalData = Encoding.UTF8.GetBytes(mySignature);
RSACryptoServiceProvider rsaProvider = (RSACryptoServiceProvider)myCert.PrivateKey;
byte[] signedSignature = signedSignature = rsaProvider.SignData(originalData, alg);
if (rsaProvider.VerifyData(originalData, alg, signedSignature))
{
}
else
{
throw new Exception("The data does not match the signature.");
}
}
}
}
}