The Kladde already uses cryptography in several places: TLS at the edge (lesson 3.0.4), Data Protection for sign-in and forms (K2), and since lesson 3.3.2 a signature of its own for the links in the booking emails, with a key from Key Vault. There, the class BookingLinks used HMACSHA256 and CryptographicOperations.FixedTimeEquals without explaining why exactly these two. This lesson makes up for that. You get to know the five tools that appear in almost every application, when each one fits, and how you spot a mistake in a review. At the end, you check the signature of the booking links against a value that was computed outside .NET.

Everything in this lesson lives in System.Security.Cryptography and so in .NET itself; no package is added. For the examples, create a folder workshop-3-3-6. Each example is a single file that you start with dotnet run <file>.cs.

Five questions, five tools

Before you choose a method, ask the question it is supposed to answer:

Question Tool In .NET
Has this content changed? Hash (SHA-256) SHA256.HashData
Does it come from someone who knows the shared key? HMAC (HMAC-SHA256) HMACSHA256.HashData
Is this the right password? Password hash (PBKDF2) Rfc2898DeriveBytes.Pbkdf2
May only the holder of the key read this? Encryption (AES-GCM) AesGcm
May anyone verify, but only one party create? Signature (ECDSA, RSA) ECDsa, RSA

On top of that comes a sixth rule that applies to all of them: Every key, every salt and every nonce comes from RandomNumberGenerator.

The most common mistakes happen when one tool is asked to answer another tool’s question: a hash as proof of origin, a fast hash for passwords, encryption without a check of authenticity.