Skip to content
Tutorials Center
My learning

Topics

Lesson 126 of 182 ยท Standard Library

Cryptography and Hashing

Learn practical C# cryptography with System.Security.Cryptography - SHA-256 hashing, HMAC, AES-GCM encryption, random bytes, and password hashing with PBKDF2.

Cryptography protects data in three main ways. Hashing turns any input into a short fixed-size fingerprint, which lets you detect changes. Message authentication (HMAC) proves that a message came from someone who holds a secret key. Encryption hides data so only the holder of a key can read it. .NET ships with a complete, well-tested implementation in System.Security.Cryptography, and the golden rule is simple: use the built-in classes and never invent your own algorithm.

This lesson shows how to hash data, compare hashes safely, create random values, authenticate messages, encrypt with AES-GCM and store passwords with PBKDF2. It assumes you know byte arrays and strings and spans at a basic level.

Cryptography is easy to use wrongly. The examples here teach the safe default building blocks, but a real security design (key storage, rotation, protocols) needs more care. For web logins, prefer ASP.NET Core Identity over writing your own password code, and prefer TLS over encrypting traffic yourself.

The four jobs and their tools

flowchart TD
    A["What do you need?"] --> B["Detect changes<br/>or fingerprint data"]
    A --> C["Prove who sent it"]
    A --> D["Keep data secret"]
    A --> E["Store a password"]
    B --> F["SHA-256 / SHA-512"]
    C --> G["HMACSHA256"]
    D --> H["AES-GCM"]
    E --> I["PBKDF2 / Argon2 with salt"]

Pick the tool by the job, not by the name of the algorithm.

Hashing with SHA-256

A hash function takes any amount of data and returns a fixed-size digest. The same input always gives the same digest, a tiny change gives a completely different one, and you cannot go back from the digest to the input. SHA-256 returns 32 bytes and is the standard choice. The static SHA256.HashData method is the shortest way to use it.

C# SHA-256 of a string

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The text is first converted to bytes, because hash functions work on bytes. Always choose the encoding explicitly (UTF-8 is the usual one). Changing a single letter ("hello" to "Hello") changes the whole digest, and the output above is the same on every computer. u8 is a UTF-8 string literal that creates a ReadOnlySpan<byte> directly.

To hash a large file without loading it into memory, pass a stream: SHA256.HashDataAsync(stream) or SHA256.HashData(stream).

Use SHA-256 or SHA-512 (or SHA-3 where the platform supports it). MD5 and SHA-1 are broken for security purposes: attackers can create two different inputs with the same hash. They are only acceptable for non-security tasks like cache keys or compatibility with an old format.

Comparing hashes safely

Never compare secret values (hashes, tokens, MACs) with == or SequenceEqual. Those stop at the first different byte, so the time they take leaks how many leading bytes were correct. An attacker can measure this. Use CryptographicOperations.FixedTimeEquals, which always takes the same time.

C# Constant-time comparison

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Random numbers for security

System.Random is predictable and must never be used for tokens, keys or salts. Use RandomNumberGenerator, which asks the operating system for cryptographically secure random bytes.

C# Secure random values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The values themselves differ on every run, which is exactly the point, so the example prints only properties that are always the same. GetInt32(from, to) avoids the subtle bias you get from bytes % n.

HMAC: proving a message is genuine

A plain hash does not prove who made it, since anyone can compute SHA-256 of any text. An HMAC mixes a secret key into the hash. Only someone who knows the key can create (or verify) the tag. Webhooks use HMACs: the sender signs the body, and the receiver recalculates the tag with the shared secret.

C# Signing and verifying with HMAC

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

An HMAC does not hide the message; it only proves integrity and origin. The key should be at least 32 random bytes and must stay secret.

Encrypting with AES-GCM

Symmetric encryption uses one key to lock and unlock data. AES is the standard algorithm, and the recommended mode is AES-GCM because it is an authenticated encryption mode: it also produces a tag that detects any tampering. If someone changes even one bit of the ciphertext, decryption throws instead of returning garbage.

You need three things for every message: a 32-byte key, a nonce (12 bytes, must be unique for each message under the same key) and the plaintext. The output is the ciphertext plus a 16-byte tag.

C# AES-GCM round trip

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Rules for AES-GCM in real code:

  • Never reuse a nonce with the same key. Reuse destroys the security. A random 12-byte nonce is fine for up to about four billion messages per key.
  • Store the nonce and tag next to the ciphertext. They are not secret. A common layout is nonce || tag || ciphertext.
  • Protect the key. Keep it in a secret store, not in source code. Encrypting data with a key that sits next to it in the repository is only decoration.
  • Use associated data (the optional last parameter) to bind a ciphertext to its context, such as a user id, so it cannot be pasted into another record.

Older code uses Aes.Create() with CBC mode. CBC alone has no tamper detection, so avoid it in new code unless a format forces it. Newer .NET versions also offer ChaCha20-Poly1305 (ChaCha20Poly1305) where the platform supports it, with the same shape of API.

Storing passwords

Passwords need special treatment. A fast hash like SHA-256 is a bad choice, because attackers can try billions of guesses per second. You need a deliberately slow and salted function. A salt is a random value stored with the hash so that two users with the same password get different hashes and precomputed tables are useless.

.NET provides PBKDF2 through Rfc2898DeriveBytes.Pbkdf2. Use a strong hash (SHA-256 or SHA-512) and a high iteration count (at least several hundred thousand for SHA-256; follow current OWASP recommendations, which grow over time).

C# Hashing and verifying a password

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The stored string contains the iteration count, the salt and the hash. Storing the iteration count lets you raise it later while old records still verify. Because the salts differ, the two records of the same password are different. Production systems should usually use ASP.NET Core Identity's PasswordHasher, which does this for you and upgrades old hashes automatically. See authentication and authorization.

Public-key cryptography in brief

Asymmetric cryptography uses a key pair: a public key you can share and a private key you keep. It is used for digital signatures (ECDsa, RSA) and for key exchange (ECDiffieHellman). Prefer elliptic curve algorithms (ECDsa.Create(ECCurve.NamedCurves.nistP256)) for new signatures, and RSA with at least 2048-bit keys when compatibility demands it. Do not encrypt big data with RSA; instead encrypt a random AES key with it, or let TLS do the work.

Common mistakes

  • Writing your own cipher or "scrambling" function. Use AES-GCM.
  • Using Random for tokens or keys. Use RandomNumberGenerator.
  • Hashing passwords with plain SHA-256 or MD5, or without a salt.
  • Comparing secrets with ==.
  • Hard-coding keys in source code, or logging them.
  • Reusing an AES-GCM nonce.
  • Calling a base64 or hex encoding "encryption". Encoding is reversible by anyone.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which class should you use to generate a secret key or session token?

    RandomNumberGenerator uses the operating system's cryptographically secure source. Random and timestamps are predictable, and a GUID is not meant to be a secret.
  2. 2. What does an HMAC add compared with a plain SHA-256 hash?

    HMAC mixes a secret key into the hash. Anyone can compute SHA-256, but only key holders can produce a valid HMAC tag. It still does not hide the message.
  3. 3. Why does AES-GCM decryption throw a CryptographicException if you flip one bit of the ciphertext?

    GCM computes an authentication tag over the ciphertext. Any modification makes the tag check fail, so you never get silently corrupted plaintext.
  4. 4. Why is a salted, slow function like PBKDF2 better than SHA-256 for passwords?

    Slow hashing limits how many guesses an attacker can try per second, and the unique salt defeats precomputed tables and hides duplicate passwords.
  5. 5. How should you compare two MAC tags?

    Regular comparisons exit early, and the timing differences can leak information. FixedTimeEquals always takes the same time for the same length.

Summary

  • Hash with SHA256.HashData (never MD5 or SHA-1 for security) and compare secrets with CryptographicOperations.FixedTimeEquals.
  • Use RandomNumberGenerator for keys, salts, nonces and tokens.
  • HMAC proves integrity and origin with a shared secret; it does not hide data.
  • Encrypt with AES-GCM: unique nonce per message, store nonce and tag with the ciphertext, protect the key.
  • Store passwords with a salted, slow function such as PBKDF2 (or Identity's PasswordHasher).
  • Do not design your own algorithms, and do not confuse encoding with encryption.

Next lesson: images with ImageSharp.