Signing data
To prove that some data has come from someone we trust, it can be signed. Actually, you don't sign the data itself, instead you sign a hash of the data. We will use the RSA algorithm combined with the SHA256 algorithm.
Signing with SHA256 and RSA
In the Ch11_Cryptography class library project, add the following code to the Protector class:
public static string PublicKey;
public static string GenerateSignature(string data)
{
byte[] dataBytes = Encoding.Unicode.GetBytes(data);
var sha = SHA256.Create();
var hashedData = sha.ComputeHash(dataBytes);
var rsa = RSA.Create();
PublicKey = rsa.ToXmlString(false); // exclude private key
var signer = new RSAPKCS1SignatureFormatter(rsa);
signer.SetHashAlgorithm("SHA256");
return Convert.ToBase64String(signer.CreateSignature(hashedData));
}
public static bool ValidateSignature(string data, string signature)
{
byte[] dataBytes = Encoding.Unicode.GetBytes(data);
var sha = SHA256.Create...