Digital Signature Implementation with C#
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
Name | Description |
---|---|
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));
reader.Close();
file.Close();
DSACryptoServiceProvider verifier = new DSACryptoServiceProvider();
verifier.FromXmlString(publicKey);
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");
else
Console.WriteLine("Signature is not verified");
reader2.Close();
file2.Close();