使用SHA256WithRSA来签名和验签(.NET/C#)

在.NET中,使用SHA256WithRSA进行签名和验签需要特定的CryptoAPI提供者。默认情况下,通过'makecert'创建的证书仅支持SHA1哈希签名。需要使用“Microsoft Enhanced RSA and AES Cryptographic Provider”来支持SHA2。若无法更改证书颁发方式,可以使用从证书导入密钥的方法创建RSACryptoServiceProvider,实现SHA256签名。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

RSACryptoServiceProvider does work with SHA2-based signatures, but you have to invest some effort into it.

When you use a certificate to get your RSACryptoServiceProvider it really matters what's the underlying CryptoAPI provider. By default, when you create a certificate with 'makecert', it's "RSA-FULL" which only supports SHA1 hashes for signature. You need the new "RSA-AES" one that supports SHA2.

So, you can create your certificate with an additional option: -sp "Microsoft Enhanced RSA and AES Cryptographic Provider" (or an equivalent -sy 24) and then your code would look like (in .NET 4.0):

var rsa = signerCertificate.PrivateKey as RSACryptoServiceProvider;
byte[] signature = rsa.SignData(data, CryptoConfig.CreateFromName("SHA256"));

 

If you are unable to change the way your certificate is issued, there is a semi-ligitimate workaround that is based on the fact that by default RSACryptoServiceProvider is created with support for SHA2. So, the following code would also work, but it is a bit uglier: (what this code does is it creates a new RSACryptoServiceProvider and imports the keys from the one we got from the certificate)

public string Sign(string contentForSign,string priKey
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值