SteelReed

Search

Search posts, questions…

5. Spring Boot

Encoding, hashing, encryption and signatures: picking the right crypto tool as a backend engineer

Which question encoding, hashing, encryption, MACs and digital signatures each answer, HMAC or signatures for APIs, symmetric vs asymmetric, what TLS protects, and managing secrets for a backend.

18 Nov 20267 min readMid

–

1. The problem

A merchant's payment request passes through the customer's browser. The dev signs it with sha256(secret + payload). An attacker appends &amount=1 without knowing the secret: a 2,000,000 VND order collects 1 VND.

2. Key idea

Ask "what do I need to guarantee?". Each answer maps to one tool:

You want to know Tool Key Reversible
Can other systems read it Encoding (Base64, URL encoding) None By anyone
Was it changed (no adversary) Hash (SHA-256) None No
Was it changed and sent by the secret holder MAC (HMAC-SHA256) Shared secret No
Same, and verifiers can't forge it Digital signature (Ed25519, ECDSA, RSA-PSS) Key pair No
Can outsiders read it Encryption (AES-GCM, ChaCha20-Poly1305) Yes By key holders
  • Base64 isn't encryption. Authorization: Basic holds the raw username:password; a JWT payload is readable on jwt.io.
  • Hash: whoever can change the data can recompute the hash, so a plain hash only guards against accidents. MD5 and SHA-1 collide: use them only for checksums and ETags.
  • Symmetric vs asymmetric differ in key distribution, not strength: AES-256 isn't weaker than RSA-3072. TLS is hybrid: ECDHE agrees on a session key, AES-GCM encrypts the data.
  • TLS protects each hop, not data that passes through the user's browser. So a payment request still needs an HMAC over HTTPS.

2.1 HMAC or a digital signature?

Approach Use when Don't use when
HMAC one-to-one integrations: merchant and payment gateway, webhooks many parties must verify but never issue
Digital signature one issuer, many verifiers: JWKS, e-invoices, non-repudiation two trusting parties that want fast and simple

HMAC has no non-repudiation: the receiver can also produce the sender's "signature".

3. In Java

JAVA
static boolean verifyHmac(byte[] key, String data, String sigHex) throws Exception {
    Mac mac = Mac.getInstance("HmacSHA512");                // never hand-roll sha256(secret + message)
    mac.init(new SecretKeySpec(key, "HmacSHA512"));
    byte[] expected = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
    byte[] given;
    try { given = HexFormat.of().parseHex(sigHex); } catch (IllegalArgumentException e) { return false; }
    return MessageDigest.isEqual(expected, given);          // constant time, not String.equals
}
// original payload -> true; payload with a changed amount -> false
 
KeyPair kp = KeyPairGenerator.getInstance("Ed25519").generateKeyPair();   // JDK 15+
Signature signer = Signature.getInstance("Ed25519");
signer.initSign(kp.getPrivate());
signer.update(payload.getBytes(StandardCharsets.UTF_8));
byte[] sig = signer.sign();                                  // 64 bytes; anyone with the public key can verify

Encryption: always spell out "AES/GCM/NoPadding"; bare "AES" is ECB. Other languages: Go hmac.Equal; Node.js crypto.timingSafeEqual.

Why sha256(secret + message) is wrong, and how the TLS handshake works
  • Length extension: SHA-256 is a Merkle–Damgård construction. Knowing sha256(secret || message) and the secret's length lets you compute sha256(secret || message || padding || extra) without the secret. HMAC (a keyed two-layer hash) is designed to block exactly this.
  • String.equals stops at the first differing byte: timing the responses lets you guess a signature byte by byte.
  • A signature isn't "encrypting the hash with the private key": that only holds for textbook RSA; ECDSA and Ed25519 have no encryption step at all.
  • TLS 1.3: the client sends an ephemeral ECDHE key; the server returns its ECDHE key, a certificate (its public key signed by a CA) and a signature proving it holds the private key; the client checks the CA chain, hostname and expiry; both derive the same session key. One round trip.
  • Disabling certificate checks (TrustManager accepting everything, HostnameVerifier returning true) still encrypts, but anyone in the middle can impersonate the server. The proper fix: put the internal CA in a dedicated truststore (Spring Boot SSL bundles).

4. Working with AI

Delegate to AI: webhook signing and verification code, truststore configuration, secret scanning in CI.

Check yourself:

  • No Base64 on passwords or card numbers as if that "protects" them.
  • Signing uses Mac.getInstance("Hmac..."), not a hash glued to a secret.
  • Signatures are compared with MessageDigest.isEqual, not equals.
  • No empty X509TrustManager or always-true HostnameVerifier.
  • Secrets are loaded from outside the code, with a key_id for rotation.

5. Exercises

Exercise 1: Pick the tool

Choose encoding, hash, MAC, digital signature, encryption or password hashing: (a) storing passwords; (b) sending an image in JSON; (c) checking a webhook really came from a partner; (d) storing national ID numbers that are sometimes displayed again; (e) access tokens verified by 30 internal services; (f) deduplicating uploaded files.

Solution to Exercise 1
  • (a) Argon2id/bcrypt: slow, salted, irreversible.
  • (b) Base64: just a format.
  • (c) HMAC with a per-partner secret, constant-time comparison, plus a timestamp against replay.
  • (d) AES-GCM in the application with envelope encryption; add a blind index if you need to search.
  • (e) Digital signatures (ES256/EdDSA) via JWKS: 30 services hold only the public key, none can forge tokens.
  • (f) SHA-256 of the content.

Exercise 2: Review "requests are signed with SHA-256"

AI wrote String sig = sha256Hex(secret + query); if (sig.equals(request.getParameter("sig"))) accept(); and noted "requests are signed against tampering". Find two bugs and name tests.

Solution to Exercise 2
  • sha256(secret + query) is open to length extension: an attacker appends parameters and still computes a valid signature. Use HmacSHA256.
  • equals isn't constant time. Use MessageDigest.isEqual on parsed bytes.
  • Tests: the original payload passes; a changed amount is rejected; a signature with a wrong last byte is rejected; malformed hex returns false instead of throwing.

Summary

  • Base64 protects nothing; a plain hash doesn't stop attackers.
  • HMAC for two parties sharing a secret; signatures for one signer, many verifiers.
  • Always AES/GCM/NoPadding, never the ECB default.
  • Never hand-roll sha256(secret + message); compare signatures in constant time.
  • TLS covers each hop only; disabling certificate checks disables TLS.

Next: Part 2: Storing passwords and encrypting personal data.

Practice interview questions on this topic

All Security questions →

Loading comments…