Tom Goff's .Net Musings

Tidbits of information regarding .Net, C#, and SQL Server.

Sign and Verify Data

leave a comment »

Recently, I needed a way to sign some text using a private RSA key and then verify it with the corresponding public key. I searched around for some simple and straight forward examples, but could not find any. MSDN has an example[^] of both generating[^] and validating[^] signatures, but the examples hard code the hash value.

In order to save others some time figuring this out, I’ve put together a sample program[^] that can generate and validate an RSA signature for a user-provided string. In addition, the program shows how to generate a hash value for a given string.

NOTE: In the interest of security, the private key should not be stored in plain-text as shown by my sample program. It is recommended that the private key be encrypted before being saved anywhere.

Below is a screen shot of the sample application. Before signing or validating the text, you must first load a public or private key, or generate a new public/private key pair. Once the key is loaded you will see the key type (“Private” or “Public”) and the key size (the application defaults to 1024).

If you load a private key, then you can both generate and validate signatures. To generate a signature, enter some text in the first text box. As you type, the base-64 encoded SHA-1 hash value will automatically update below it. Next, when you click the “Generate Signature” button you will see the base-64 encoded RSA signature. Finally, you can validate the signature by clicking “Validate Signature” button, obviously.

If you have a public key loaded, then you can only validate signatures. If you have a public/private key pair then you can load the private key, generate the signature, load the public, then validate the signature.

You can try changing the text after generating the signature, but before validating the signature. This should invalidate the signature, resulting in a message box saying as much. You can also try changing the signature.

There are similar built-in .Net classes, to the ones used by the sample application, for working with DSA (instead of RSA) keys and signatures. Therefore, the translation should be trivial.

Hopefully, this will help someone else save some time when trying to sign some data.


Written by Tom

August 30, 2007 at 12:02 pm

Posted in .Net, C#, Security

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: