C#: message authentication with HMAC-SHA256

A plain hash lets anyone recompute a digest after changing a message. An HMAC mixes a secret key into the hash, so only someone who knows the key can produce a valid tag. The receiver recomputes the tag with the shared key and compares it with the one received. If they match, the message is authentic and unmodified.

C#
using System;
using System.Security.Cryptography;
using System.Text;

class Program {
  static void Main() {
    byte[] key = Encoding.UTF8.GetBytes("Jefe");
    byte[] message = Encoding.UTF8.GetBytes("what do ya want for nothing?");
    byte[] tampered = Encoding.UTF8.GetBytes("what do ya want for something?");

    using var hmac = new HMACSHA256(key);
    byte[] tag = hmac.ComputeHash(message);
    Console.WriteLine(Convert.ToHexString(tag).ToLowerInvariant());

    byte[] again = hmac.ComputeHash(message);
    Console.WriteLine("same message valid: " + CryptographicOperations.FixedTimeEquals(tag, again));
    byte[] forged = hmac.ComputeHash(tampered);
    Console.WriteLine("tampered message valid: " + CryptographicOperations.FixedTimeEquals(tag, forged));
  }
}
Read the full lesson