用C#写一个方法验证刚才的签名是否正确
时间: 2023-10-08 21:12:14 浏览: 40
好的,以下是用 C# 实现验证签名是否正确的代码:
```csharp
using System;
using System.Security.Cryptography;
using System.Text;
class Program
{
static void Main(string[] args)
{
string content = "待签名的内容";
string signature = "签名结果";
string publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCzjC3SZz3QjwGJLr7B+2B6Ct/2Yvq6K5T8amFvYrUv9zQ9/q0MvJq0VJQivzJFb9zEgF4Jdf5UvJq3zGyUdDzNEfCQYRtHgJzX+L8h9hwgV+LUBsmJZL24f3VgHr6/8Ei8Zd3i4n+2o6sG0JX1X3LrRkz8J6I7qZCmpwM3rV0Lc4QIDAQAB";
byte[] publicKeyBytes = Convert.FromBase64String(publicKey);
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.ImportCspBlob(publicKeyBytes);
byte[] contentBytes = Encoding.UTF8.GetBytes(content);
byte[] signatureBytes = Convert.FromBase64String(signature);
bool verified = rsa.VerifyData(contentBytes, new SHA1CryptoServiceProvider(), signatureBytes);
Console.WriteLine($"验证结果:{verified}");
}
}
```
需要注意的是,验证签名的方法需要用到公钥,因此需要将公钥字符串转换成字节数组,并导入到 `RSACryptoServiceProvider` 对象中。如果签名正确,`VerifyData` 方法将会返回 `true`。