如何使用 .NET 对文件进行签名,以及如何在读取后验证生成的 key 是否有效?
我的目标是拥有一个包含一些值和生成的 key 的文本文件。然后,我希望能够检查文件中生成的 key ,以便在我将文件发送给客户后没有人篡改文件中的值。
更新:
找到了 here在答案的一些帮助下。
最佳答案
尝试这个:
class Program
{
static byte[] Sign(string message, RSAParameters key)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.ImportParameters(key);
byte[] toSign = Encoding.Unicode.GetBytes(message);
return rsa.SignData(toSign, "SHA1");
}
static bool Verify(string message, byte[] signature, RSAParameters key)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.ImportParameters(key);
byte[] toVerify = Encoding.Unicode.GetBytes(message);
return rsa.VerifyData(toVerify, "SHA1", signature);
}
static void Main(string[] args)
{
string message = "Let's sign this message.";
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); // Creates a new RANDOM key.
RSAParameters privatekey = rsa.ExportParameters(true);
RSAParameters publickey = rsa.ExportParameters(false);
byte[] signature = Sign(message, privatekey);
if (Verify(message, signature, publickey))
{
Console.WriteLine("It worked!");
}
}
}
请务必注意,每次启动此程序时都会生成一个新的公钥/私钥对。为了做你想做的事,你需要在两端使用之前保存公钥/私钥对。您的公钥是您唯一需要验证的东西,因此您的私钥不会发布给客户端。
您可能需要查看 ExportParameters 或 ExportCspBlob 来完成保存/加载公钥/私钥对。
关于.net - 在 .NET 中使用私钥对文件进行签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/720673/