IC Improve Code Recipes

Recipe 7.3 · C#

Hashing and HMAC with SHA-256

Problem

You need to check that a file wasn't corrupted in transfer, or that a webhook request really came from your payment provider and wasn't altered. The legacy code uses MD5 for the first and a shared secret in a query string for the second.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

C#
// Not this: MD5 checksum, and a "secret" compared with ==.
string checksum = BitConverter.ToString(
    MD5.Create().ComputeHash(File.ReadAllBytes(path)));

if (Request.QueryString["key"] == "abc123")
{
    ProcessWebhook(Request.InputStream);
}

The improved recipe

Use SHA-256 for checksums and HMAC-SHA-256 with a timestamp for message authentication. Compare signatures with FixedTimeEquals.

C#
using System;
using System.Globalization;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ImproveCode.Security;

public static class Checksums
{
    public static async Task<string> Sha256OfFileAsync(
        string path, CancellationToken ct = default)
    {
        await using FileStream stream = File.OpenRead(path);
        byte[] hash = await SHA256.HashDataAsync(stream, ct);
        return Convert.ToHexString(hash);
    }

    public static string Sha256OfText(string text) =>
        Convert.ToHexString(
            SHA256.HashData(Encoding.UTF8.GetBytes(text)));
}

/// <summary>Signs and verifies "{timestamp}.{body}" with
/// HMAC-SHA-256, the scheme most webhook providers use.</summary>
public sealed class WebhookSigner
{
    private readonly byte[] _secret;
    private readonly TimeProvider _time;
    private readonly TimeSpan _tolerance;

    public WebhookSigner(
        byte[] secret, TimeProvider time, TimeSpan? tolerance = null)
    {
        ArgumentNullException.ThrowIfNull(secret);
        ArgumentOutOfRangeException.ThrowIfLessThan(secret.Length, 32);
        _secret = (byte[])secret.Clone();
        _time = time;
        _tolerance = tolerance ?? TimeSpan.FromMinutes(5);
    }

    public string Sign(ReadOnlySpan<byte> body, long unixSeconds) =>
        Convert.ToHexString(Compute(body, unixSeconds));

    public bool IsValid(
        ReadOnlySpan<byte> body, long unixSeconds, string signature)
    {
        long now = _time.GetUtcNow().ToUnixTimeSeconds();
        if (Math.Abs(now - unixSeconds) > _tolerance.TotalSeconds)
        {
            return false; // too old or from the future: replay
        }

        byte[] provided;
        try
        {
            provided = Convert.FromHexString(signature);
        }
        catch (FormatException)
        {
            return false;
        }

        byte[] expected = Compute(body, unixSeconds);
        return CryptographicOperations.FixedTimeEquals(
            expected, provided);
    }

    private byte[] Compute(ReadOnlySpan<byte> body, long unixSeconds)
    {
        string prefix =
            unixSeconds.ToString(CultureInfo.InvariantCulture) + ".";

        using var hmac = IncrementalHash.CreateHMAC(
            HashAlgorithmName.SHA256, _secret);
        hmac.AppendData(Encoding.ASCII.GetBytes(prefix));
        hmac.AppendData(body);
        return hmac.GetHashAndReset();
    }
}

How it works

A hash is a fingerprint: anyone can compute it, and any change to the input changes it. That makes SHA-256 right for detecting accidental corruption and for content-addressed caching, but useless for proving who sent a message, because an attacker who changes the file can recompute the hash too. HashDataAsync streams the file, so a 4 GB export doesn't need 4 GB of memory.

An HMAC mixes a secret key into the hash. Only someone who has the key can produce a valid signature, and changing a byte of the body invalidates it. The sender computes HMAC(secret, timestamp + "." + body) and sends the timestamp and signature in headers; the receiver recomputes and compares.

The timestamp is part of the signed content, so it can't be altered, and the tolerance check rejects requests replayed more than five minutes later. Injecting TimeProvider (built in since .NET 8) makes that check testable with a fake clock.

FixedTimeEquals matters here more than anywhere else. The signature is compared against attacker-controlled input on every request, which is exactly the situation where early-exit comparison could leak information through timing. It also returns false for arrays of different lengths, so a truncated signature fails cleanly.

Variations and pitfalls

  • Sign the raw request body bytes exactly as received. If you deserialize and reserialize the JSON first, whitespace or property order changes and valid signatures fail.
  • In ASP.NET Core, call Request.EnableBuffering(), read the body into a byte array for the check, then rewind the stream if model binding needs it.
  • Follow each provider's documented scheme exactly. Some sign only the body, some use Base64 instead of hex, some include the URL. The class above is the common pattern, not a standard.
  • Don't use plain SHA-256 to "hash" a secret for storage when the secret has low entropy, such as a password or a PIN. That is Recipe 7.1's job. SHA-256 is fine for high-entropy random tokens (Recipe 7.4).
  • MD5 and SHA-1 are acceptable only for non-security uses such as matching a legacy system's checksum format. Mark those call sites with a comment so the next reviewer doesn't have to guess.