Skip to content

Instantly share code, notes, and snippets.

@PaulNichols
Last active March 1, 2017 22:37
Show Gist options
  • Save PaulNichols/bc6fcc619fadb13242f0ec1db0460e87 to your computer and use it in GitHub Desktop.
Save PaulNichols/bc6fcc619fadb13242f0ec1db0460e87 to your computer and use it in GitHub Desktop.
using System.Security.Cryptography;
namespace CryptographyInDotNet
{
public class DigitalSignature
{
private RSAParameters _publicKey;
private RSAParameters _privateKey;
public void AssignNewKey()
{
using (var rsa = new RSACryptoServiceProvider(2048))
{
rsa.PersistKeyInCsp = false;
_publicKey = rsa.ExportParameters(false);
_privateKey = rsa.ExportParameters(true);
}
}
public byte[] SignData(byte[] hashOfDataToSign)
{
using (var rsa = new RSACryptoServiceProvider(2048))
{
rsa.PersistKeyInCsp = false;
rsa.ImportParameters(_privateKey);
var rsaFormatter = new RSAPKCS1SignatureFormatter(rsa);
rsaFormatter.SetHashAlgorithm("SHA256");
return rsaFormatter.CreateSignature(hashOfDataToSign);
}
}
public bool VerifySignature(byte[] hashOfDataToSign, byte[] signature)
{
using (var rsa = new RSACryptoServiceProvider(2048))
{
rsa.ImportParameters(_publicKey);
var rsaDeformatter = new RSAPKCS1SignatureDeformatter(rsa);
rsaDeformatter.SetHashAlgorithm("SHA256");
return rsaDeformatter.VerifySignature(hashOfDataToSign, signature);
}
}
}
}
using System;
using System.Security.Cryptography;
using System.Text;
namespace CryptographyInDotNet
{
class Program
{
static void Main()
{
var document = Encoding.UTF8.GetBytes("Document to Sign");
byte[] hashedDocument;
using (var sha256 = SHA256.Create())
{
hashedDocument = sha256.ComputeHash(document);
}
var digitalSignature = new DigitalSignature();
digitalSignature.AssignNewKey();
var signature = digitalSignature.SignData(hashedDocument);
var verified = digitalSignature.VerifySignature(hashedDocument, signature);
Console.WriteLine("Digital Signature Demonstration in .NET");
Console.WriteLine("---------------------------------------");
Console.WriteLine();
Console.WriteLine();
Console.WriteLine(" Original Text = " +
Encoding.Default.GetString(document));
Console.WriteLine();
Console.WriteLine(" Digital Signature = " +
Convert.ToBase64String(signature));
Console.WriteLine();
Console.WriteLine(verified
? "The digital signature has been correctly verified."
: "The digital signature has NOT been correctly verified.");
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment