使用.NET中的私钥对文件进行签名 [英] Sign a file using a private key in .NET

查看:93
本文介绍了使用.NET中的私钥对文件进行签名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何使用.NET签名文件,如何验证生成的密钥是否是有效的?一旦我读了它?

How do I sign a file using .NET and how do I then validate that the generated key is a valid one once I read it?

我的目标是具有一些带有一些值的文本文件和一个生成的密钥。然后,我想要检查文件中生成的密钥,一旦我将文件发送给客户,就不会篡改文件中的值。

My goal is to have a text file with some values and a generated key. I then want to be able to check that generated key in the file to make no one has tampered with the values in the file once I sent the file to a customer.

更新:
从答案的一些帮助中找到 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!");
        }
    }
}

请注意,每次启动此程序时都会生成新的公钥/私钥。为了做你想要的,你需要在使用它们之前保存公共/私人密钥对。您的公钥是您唯一需要验证的密钥,因此您的私钥不会被发送给客户端。

It's important to note that a new public/private keypair is generated everytime you start this program. In order to do what you want, you'll want to save the public/private keypair before using it at both ends. Your public key is the only thing you need to verify, so your private key will not be published to the client.

您可能需要查看ExportParameters或ExportCspBlob完成保存/加载公共/私人密钥对。

You might want to take a look at ExportParameters or ExportCspBlob to accomplish saving/loading the public/private keypair.

这篇关于使用.NET中的私钥对文件进行签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆