📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is the difference between hashing, encryption and encoding? Give a .NET example of each, and explain why storing SHA256(password) is not proper password hashing.

Distinguishes hashing, encryption and encoding by purpose and reversibility, with .NET APIs for each, and explains why a fast hash like SHA-256 is unsafe for passwords.

Junior Theory Beginner cryptography encoding encryption hashing password-hashing security

🎯 Key points

  • Encoding (Base64, UTF-8) is a reversible format change with no key: zero secrecy
  • Encryption (AES, RSA) is reversible only with a key: confidentiality
  • Hashing (SHA-256) is one-way, fixed-size output: integrity and fingerprints; HMAC adds a secret key for authenticity
  • SHA-256, SHA-1 and MD5 run billions of times per second on a GPU, so fast hashes fall to brute force and rainbow tables
  • Passwords need a slow KDF (PBKDF2, bcrypt, Argon2id) with a per-user salt from a CSPRNG (RandomNumberGenerator)
  • Don't encrypt passwords: if the key is compromised, every password is recoverable at once
  • Base64 in a JWT payload or config is not protection

⏱ 30-second answer

They answer different questions. Encoding (Base64, UTF-8, URL encoding) changes the format of data so another system can carry it; anyone can reverse it, there is no key. Encryption (AES, RSA) makes data confidential: it is reversible, but only with the key. Hashing (SHA-256) is a one-way fingerprint: same input, same fixed-size output, and you can't get the input back, so it is used for integrity checks and comparisons.

SHA256(password) is still wrong for passwords because SHA-256 is designed to be fast: a single GPU tries billions of guesses a second, and without a salt identical passwords share a hash and precomputed tables work. Passwords need a deliberately slow, salted key-derivation function such as PBKDF2, bcrypt or Argon2id. The trade-off: you spend tens of milliseconds per login so an attacker spends years per password.

🗣 Full answer (senior)

How I would answer this in an interview

"I separate them by what they protect. Encoding protects nothing: it is a reversible format change, like Base64 turning bytes into text for a JSON field or an HTTP header. No key, so anyone can decode it. Encryption protects confidentiality: AES or RSA turns plaintext into ciphertext, and only someone with the key gets the plaintext back. Hashing protects integrity: SHA-256 maps any input to a 32-byte digest, it is one-way, and a one-bit change in the input changes the whole output, which is why we use it for file checksums, ETags and signatures.

In .NET those are Convert.ToBase64String, AesGcm and SHA256.HashData. They live in very different places: Base64 is in System, the other two in System.Security.Cryptography.

The mistake I see is treating SHA-256 as password storage. It is one-way, so it sounds right, but it is built for speed. A modern GPU computes billions of SHA-256 hashes a second, so an eight-character password falls in hours after a database leak, and without a per-user salt two users with Winter2026! have the same hash and precomputed rainbow tables work. Password storage needs a password hashing function: a random salt per user plus a tunable work factor, like PBKDF2 with hundreds of thousands of iterations, bcrypt or Argon2id. In ASP.NET Core you get that for free from Identity's PasswordHasher<TUser>. And never encrypt passwords: if the key leaks with the database, every password leaks with it.

So my one-liner is: encoding is for transport, encryption is for secrets you need back, hashing is for things you only need to compare, and passwords need a slow hash."


The three side by side

Encoding Encryption Hashing
Goal Format / transport Confidentiality Integrity, comparison
Reversible? Yes, by anyone Yes, with the key No
Key? None Symmetric or key pair None (HMAC adds a key)
Output size Grows with input Input size + nonce/tag Fixed (SHA-256 = 32 bytes)
.NET API Convert.ToBase64String, Encoding.UTF8 AesGcm, RSA.Encrypt SHA256.HashData, HMACSHA256.HashData
Typical use JWT segments, data URIs Card numbers, tokens at rest Checksums, ETags, dedup keys

Why fast hashes fail for passwords

Property SHA-256 Password hash (PBKDF2/bcrypt/Argon2id)
Speed Billions/sec on a GPU Tunable: aim for roughly 50–250 ms on your server
Salt None built in Random per-user salt stored with the hash
Memory-hard No Argon2id (and scrypt) yes
Upgrade path None Work factor stored in the hash, rehash on login

When to use which

  • Need the original value later (a bank account number to send to a payment provider)? Encrypt it.
  • Only need to check equality (passwords, API keys)? Hash it: slow hash for low-entropy passwords, SHA-256 is fine for random 256-bit API keys.
  • Need to put bytes in a text channel? Encode it, and remember that is not protection.

Production example

A legacy system I'd describe stored SHA256(password) for [about 200,000] users. A pen-test cracked [40%] of a sample offline in under a day on one GPU. Moving to Identity's PasswordHasher with rehash-on-login upgraded [over 80%] of active users within a month, and the remainder were forced through a reset.

🔍 What the interviewer is checking

Checks that the candidate knows the purpose of each primitive and understands why password storage needs a slow, salted function rather than any one-way hash.

Green flags

  • Defines each by purpose and reversibility, not just by name
  • Explains brute force and salts, mentions a work factor and names PBKDF2/bcrypt/Argon2id
  • Knows Identity's PasswordHasher exists and is the default answer in ASP.NET Core
  • Notes that a JWT payload is only encoded

Red flags

  • Says Base64 or SHA-256 "encrypts"
  • Suggests encrypting passwords
  • Thinks a salt must be secret or that one global salt is enough

📚 Learn in depth

1. Three different jobs

Encoding:   bytes  --Base64-->  text      --Base64 decode-->  bytes   (no secret)
Encryption: plain  --AES(key)-> cipher    --AES(key)-->       plain   (needs key)
Hashing:    data   --SHA-256->  32 bytes  --X--> (no way back)

Encoding is a bijection defined by a public spec. Encryption is a keyed bijection: without the key it should look random. A hash function is a many-to-one mapping from an unbounded input to a fixed output; security comes from being pre-image resistant (can't find an input for a given hash) and collision resistant (can't find two inputs with the same hash).

2. What a password attacker actually does

After a breach the attacker has hash and (maybe) salt. They don't reverse the hash; they guess: take a candidate from a wordlist, hash it, compare. So the defence is to make each guess expensive.

guesses/sec  x  seconds  =  passwords tried
SHA-256 on one GPU: ~10^9-10^10/s  ->  every 8-char lowercase+digit password in about an hour or less
PBKDF2-SHA512, 210k iterations: a few thousand/s per GPU  ->  orders of magnitude slower
  • Salt: 16+ random bytes per user, stored next to the hash. It defeats rainbow tables and stops one guess testing every user at once.
  • Work factor: iterations (PBKDF2), cost (bcrypt) or memory + iterations (Argon2id). Memory-hard functions also blunt GPUs and ASICs, which have lots of cores but little fast memory per core.
  • Pepper (optional): a secret key held outside the database (Key Vault) mixed in, so a DB-only leak isn't enough.

3. How .NET implements each

  • Convert.ToBase64String / Base64Url (System.Buffers.Text.Base64Url, .NET 9+) for encoding.
  • SHA256.HashData(ReadOnlySpan<byte>) is a one-shot static, allocation-free, backed by the OS crypto library (CNG on Windows, OpenSSL on Linux).
  • Rfc2898DeriveBytes.Pbkdf2(password, salt, iterations, HashAlgorithmName.SHA512, 32) is the static PBKDF2.
  • PasswordHasher<TUser> (Identity) writes a versioned format: a marker byte, PRF, iteration count, salt, subkey. Since .NET 7 the default is PBKDF2-HMAC-SHA512 with 100,000 iterations, 128-bit salt and 256-bit subkey; PasswordHasherOptions.IterationCount lets you raise it.
  • bcrypt and Argon2 are not in the BCL; use a vetted package (e.g. BCrypt.Net-Next, Konscious.Security.Cryptography.Argon2).

4. Where people blur the lines

  • A JWT payload is Base64Url-encoded, not encrypted: anyone can read it at jwt.ms.
  • "Encrypted" config that the app decrypts with a key stored beside it is obfuscation.
  • HMAC is a keyed hash: integrity and authenticity, still not confidentiality.

Try it yourself

  1. Base64-encode a JSON string, paste it into any online decoder, and note there's nothing secret about it.
  2. Benchmark SHA256.HashData against Rfc2898DeriveBytes.Pbkdf2 with 210,000 iterations using BenchmarkDotNet; compare ops/sec.
  3. Hash the same password twice with PasswordHasher<object> and observe two different outputs, then verify both.
  4. Hash two strings differing by one character with SHA-256 and count the differing hex digits (the avalanche effect).

💻 Code

Each operation with the right .NET API; the comments explain why the password case is different.

using System.Security.Cryptography;
using System.Text;
using Microsoft.AspNetCore.Identity;

namespace CryptoBasics;

public static class Demo
{
    public static void Run()
    {
        byte[] data = Encoding.UTF8.GetBytes("invoice-42");

        // Encoding: reversible by anyone, no key. Transport only.
        string encoded = Convert.ToBase64String(data);
        byte[] decoded = Convert.FromBase64String(encoded);

        // Hashing: one-way, fixed 32 bytes. Fine for checksums and random API keys.
        byte[] digest = SHA256.HashData(data);
        Console.WriteLine(Convert.ToHexString(digest));

        // Encryption: reversible with the key. Authenticated (AES-GCM) so tampering is detected.
        byte[] key = RandomNumberGenerator.GetBytes(32);
        byte[] nonce = RandomNumberGenerator.GetBytes(AesGcm.NonceByteSizes.MaxSize); // 12 bytes
        byte[] cipher = new byte[data.Length];
        byte[] tag = new byte[16];
        using var aes = new AesGcm(key, tagSizeInBytes: 16);
        aes.Encrypt(nonce, data, cipher, tag);

        // Passwords: slow, salted, versioned. Never SHA256(password), never encryption.
        var hasher = new PasswordHasher<object>();
        string stored = hasher.HashPassword(user: new object(), "correct horse battery staple");
        var result = hasher.VerifyHashedPassword(new object(), stored, "correct horse battery staple");
        Console.WriteLine(result); // Success (or SuccessRehashNeeded after you raise the work factor)
    }
}

⚠ Common mistakes

  • Mistake: Calling Base64 "encryption". Why it is wrong: it has no key; anyone decodes it in a second. Instead: use AES-GCM or Data Protection when the value must be secret.
  • Mistake: Storing SHA256(password), or keeping legacy MD5/SHA-1 password hashes. Why it is wrong: fast hashes allow billions of guesses per second, MD5 and SHA-1 also have practical collision attacks, and unsalted hashes are identical for identical passwords. Instead: use PasswordHasher<TUser>, PBKDF2 with a high iteration count, bcrypt or Argon2id, and migrate legacy hashes.
  • Mistake: Encrypting passwords so support can "recover" them. Why it is wrong: encryption is fine for data you need back, but for passwords the key becomes a single point of failure: compromise it and every password is exposed, and users reuse passwords elsewhere. Instead: hash them and offer a reset flow.
  • Mistake: Using one global salt, or generating salts with System.Random or a GUID. Why it is wrong: a shared or predictable salt lets one guess test many accounts and enables precomputation. Instead: at least 16 bytes per password from RandomNumberGenerator.GetBytes (Identity does this for you).
  • Mistake: Comparing hashes with == or SequenceEqual. Why it is wrong: early-exit comparison leaks timing. Instead: CryptographicOperations.FixedTimeEquals.
  • Mistake: Using a plain hash where you need authenticity, e.g. SHA256(payload) on a webhook. Why it is wrong: anyone can recompute it after tampering. Instead: a keyed hash, HMACSHA256.HashData(secret, payload).
  • Mistake: Putting sensitive claims in a JWT because it "looks encrypted". Why it is wrong: the payload is only Base64Url encoded. Instead: keep tokens minimal or use JWE where confidentiality is required.

🏛 Senior insight: trade-offs

The useful senior framing is entropy: the right primitive depends on how guessable the input is. A 256-bit random API key can't be brute-forced (29 to 10^12 likely candidates, which a GPU running a fast hash exhausts in minutes to hours. A slow KDF adds the missing difficulty: if each guess costs 100 ms instead of a nanosecond, the same search takes years. That is also why I'd rather move password handling to an identity provider (Entra External ID, Auth0) than tune it myself.

Input Primitive Why When not
User password PBKDF2/bcrypt/Argon2id, salted Low entropy, must slow guessing Never use a fast hash
Random API key (32 bytes) SHA-256 High entropy, fast lookup by hash Not for human-chosen secrets
Message that must not be forged HMAC-SHA256 Keyed integrity and authenticity When you need non-repudiation (use signatures)
Value you must read back AES-GCM / Data Protection / Key Vault Confidentiality with key control If you only need to compare, hash instead
Data in a text channel Base64 / Base64Url Format only Never as protection

Measure the work factor on production hardware: target roughly 50–250 ms per hash and watch login CPU, because a slow hash also makes login a DoS target, so pair it with rate limiting.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions that Identity's PasswordHasher handles password storage. Why: Checks whether they know what else Identity provides and when to use an external identity provider instead.
    How to answer

    ASP.NET Core Identity is a membership library: user and role stores (usually EF Core), password hashing with PasswordHasher (PBKDF2 with HMAC-SHA512 and 100,000 iterations), lockout after failed attempts, email confirmation, password reset tokens, two-factor with authenticator apps and recovery codes, the security stamp, and since .NET 10 passkeys. MapIdentityApi adds ready-made register, login and refresh endpoints for SPAs and mobile apps.

    Use it when one app owns its own users. Choose an external identity provider (Microsoft Entra ID for staff, Entra External ID, Auth0 or similar for customers) when you need single sign-on across apps, federation with other organisations, conditional access, or you don't want to own password security and compliance yourself.

    The trade-off: Identity is free and fully in your control, but every security feature and incident is yours to run.

  2. When: Candidate says a JWT payload is only Base64Url encoded. Why: Checks understanding of JWT structure, signing and what must not go in a token.
    How to answer

    A JWT is three base64url parts, header.payload.signature. The header says which algorithm and key (alg, kid) signed it; the payload holds claims (iss, aud, sub, exp, scopes); the signature proves nobody changed them. It is signed, not encrypted, so anyone holding it can read it: no personal or secret data.

    • RS256/ES256: the identity provider signs with a private key and APIs verify with the public key from its JWKS endpoint. HS256 uses one shared secret, so every verifier could also forge tokens.
    • In ASP.NET Core, AddJwtBearer with Authority and Audience validates issuer, audience, lifetime and signature (with a 5-minute ClockSkew).

    The trade-off: validation is local and fast, but a stolen token is valid until exp, so keep access tokens short-lived.

↩ Usually asked after

More in Cryptography

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me