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)); ...

Get C# 6 and .NET Core 1.0: Modern Cross-Platform Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.