Digital Signature Implementation with C#

Digital signature can be appended to a file in order to validate this file as a file created by the user with the specific private key. This is important for one main reason; it authenticates the identity of the user when he/she is transmitting the file. It also helps to protect integrity of data. We can also use public key algorithm to sign data digitally and data signed with the public key can be verified by anyone since public key is accessible and included.

One important thing to remember is that digital signature does not protect file but rather guarantees that data was not modified during transmission between two parties.

Two classes are used to create and verify digital signatures: DSACryptoServiceProvider and RSACryptoServiceProvider. They both have same methods


SignHash Signature from hash value
SignData Generate hash value from the file
VerifyHash Validates signature from hash value
VerifyData Validates signature for a given file

DSACryptoServiceProvider MySigner = new DSACryptoServiceProvider();

FileStream file = new FileStream(args[0], FileMode.Open, FileAccess.Read);
BinaryReader reader = new BinaryReader(file);
byte[] data = reader.ReadBytes((int)file.Length);

byte[] signature = MySigner.SignData(data);

string publicKey = MySigner.ToXmlString(false);
Console.WriteLine("Signature: " + Convert.ToBase64String(signature));

DSACryptoServiceProvider verifier = new DSACryptoServiceProvider();


FileStream file2 = new FileStream(args[0], FileMode.Open, FileAccess.Read);
BinaryReader reader2 = new BinaryReader(file2);
byte[] data2 = reader2.ReadBytes((int)file2.Length);

if (verifier.VerifyData(data2, signature))
    Console.WriteLine("Signature is not verified");