Sign the file using the private key in .NET.

How to sign a file using .NET and how can I verify that the generated key is valid after reading it?

My goal is to have a text file with some values โ€‹โ€‹and a generated key. Then I want to check that the generated key is in the file so that no one changes the values โ€‹โ€‹in the file after sending the file to the client.

Update: Found here with some help from the answers.

+6
encryption
source share
3 answers

Try the following:

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 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 is important to note that when creating this program, a new public / private key pair is created. To do what you want, you want to keep the public / private key pair before using it from both ends. Your public key is the only thing you need to verify, so your private key will not be published to the client.

You might want to take a look at ExportParameters or ExportCspBlob to save / load a public / private key pair.

+6
source share

If you want to sign the assembly, jaloplo gave a solution.

If you want to sign some files created by your program, look at the DSACryptoServiceProvider class in the System.Security.Cryptography namespace.

+3
source share

You have two options:

  • Once upon a project properties in the Icon option.
  • The second edits the AssemblyInfo.cs file and adds the commands for using the generated sn: [assembly: AssemblyKeyFile("..\\..\\SN_Generated.snk")]
-2
source share

All Articles