首页 > 解决方案 > .Net Core 3.0 中的 RSA.Verify 问题

问题描述

我正在与通过字节数组向我发送证书的第 3 方合作。他们在 XML 文档中向我发送了 3 个字符串,其中包括 x509Data、SignatureValue 和 DigestValue(用于调试)。

他们希望我使用 x509Data 证书中包含的证书公钥来验证 SignatureValue 是否有效。我很好地填充了证书,但是当我尝试验证时,它总是返回 false。

这是我的代码:

byte[] SignatureValueBytes = Convert.FromBase64String(Signature.SignatureValue);
byte[] x509DataBytes = Convert.FromBase64String(Signature.x509Data);
byte[] DigestValueBytes = Convert.FromBase64String(Signature.DigestValue);
X509Certificate2 cert = new X509Certificate2(x509DataBytes);
using (RSA RSA = (RSA)cert.PublicKey.Key)
{
    bool a = RSA.VerifyData(x509DataBytes, SignatureValueBytes, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
}

Signature.* 是来自 XML 文件的字符串。某个善良的灵魂可以指出我在哪里出错了吗?

标签: c#encryption.net-core

解决方案


您编写的代码正在尝试验证这SignatureValueBytesx509DataBytes使用 RSASSA-PKCS1-SHA256 签名的签名。

假设您正确理解了 RSASSA-PKCS1-SHA256 部分,您可能想要使用VerifyHashandDigestValueBytes而不是VerifyDataand x509DataBytes。(你也想用cert.GetRSAPublicKey()代替cert.PublicKey.Key

byte[] SignatureValueBytes = Convert.FromBase64String(Signature.SignatureValue);
byte[] x509DataBytes = Convert.FromBase64String(Signature.x509Data);
byte[] DigestValueBytes = Convert.FromBase64String(Signature.DigestValue);
X509Certificate2 cert = new X509Certificate2(x509DataBytes);
using (RSA RSA = cert.GetRSAPublicKey())
{
    bool a = RSA.VerifyHash(DigestValueBytes, SignatureValueBytes, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
}

推荐阅读