Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

Explain the difference between MessageDigest, Mac, Signature and Cipher in the Java Cryptography Architecture, and when to use SecureRandom.

In the Java Cryptography Architecture, MessageDigest computes a hash such as SHA-256 that detects changes but uses no key, Mac such as HmacSHA256 uses a shared secret key so only key holders can create or check the tag, Signature signs with a private key and verifies with the public key (RSA, ECDSA, EdDSA), and Cipher encrypts and decrypts data. SecureRandom is the generator to use for anything secret or unpredictable, such as keys, IVs, tokens and salts, because java.util.Random is predictable.

Why this question is asked

These four classes look similar: each takes bytes and produces bytes. Mixing them up is a common source of real vulnerabilities, such as using a plain hash where a keyed MAC was needed, so an attacker can recompute the "signature" of a tampered message. Interviewers ask this to see whether we know what each primitive guarantees and when to choose it. In this answer, we will recap the JCA's provider model, then walk through MessageDigest, Mac, Signature and Cipher with runnable examples, compare what each one guarantees, and finish with SecureRandom.

1A Quick Recap of the JCA

The Java Cryptography Architecture is a set of engine classes, each created with a getInstance("algorithm") factory. The actual implementation comes from a provider, such as the built-in SunJCE, or a third-party one like Bouncy Castle. Our code names the algorithm; the JDK finds a provider that supports it. That is why the same code can run with hardware security modules or FIPS providers without changes.

Each engine answers a different question. Has this data changed? Did someone with our shared key produce it? Did the holder of this private key produce it? Can only the key holder read it? Keeping those questions apart is the whole topic.

2MessageDigest: A Fingerprint Without a Key

MessageDigest computes a cryptographic hash, a fixed-size fingerprint of any input. SHA-256 always produces 32 bytes, the same input always gives the same output, and finding another input with the same hash is infeasible. We use it to check that a downloaded file matches a published checksum, to deduplicate content, or as a building block.

Java
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] h = md.digest("hello".getBytes(StandardCharsets.UTF_8));
System.out.println(h.length); // 32
System.out.println(HexFormat.of().formatHex(h)); // 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824

Notice what is missing: a key. Anyone can compute SHA-256 of anything. So if an attacker changes a message, they can simply compute the new hash too. A hash proves integrity only when the hash itself arrives through a trusted channel, such as a checksum on a trusted website. And a plain hash is not suitable for storing passwords, because it is too fast; that needs bcrypt or Argon2.

3Mac: A Tag Only Key Holders Can Make

A Mac (message authentication code) mixes a secret key into the computation. HmacSHA256 is the common choice. Both sides share the key: the sender computes the tag, the receiver recomputes it and compares. An attacker without the key cannot produce a valid tag for a changed message. Webhooks from payment providers and signed cookies typically use HMAC.

Java
SecretKey key = new SecretKeySpec(sharedSecretBytes, "HmacSHA256");
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(key);
byte[] tag = mac.doFinal(body.getBytes(StandardCharsets.UTF_8)); // 32 bytes
boolean ok = MessageDigest.isEqual(tag, receivedTag); // constant-time comparison

The limitation is that both sides hold the same key, so a MAC cannot prove which of them created a message. That is fine between our service and one partner, but it does not work when many parties must verify without being able to forge.

4Signature: Private Key Signs, Public Key Verifies

Signature uses a key pair. The private key signs; the public key, which we can publish to anyone, verifies. So everyone can check a signature, but only the private key holder can create one. JWTs signed with RS256 or ES256, signed software releases and certificates all work this way. Common algorithms are RSA (for example SHA256withRSA or RSASSA-PSS), ECDSA (SHA256withECDSA) and EdDSA (Ed25519, available in the JDK since Java 15).

Java
KeyPair kp = KeyPairGenerator.getInstance("Ed25519").generateKeyPair();
Signature signer = Signature.getInstance("Ed25519");
signer.initSign(kp.getPrivate());
signer.update(doc);
byte[] sig = signer.sign(); // 64 bytes for Ed25519
Signature verifier = Signature.getInstance("Ed25519");
verifier.initVerify(kp.getPublic());
verifier.update(doc);
System.out.println(verifier.verify(sig)); // true
doc[0] ^= 1; // change one bit
verifier.initVerify(kp.getPublic()); verifier.update(doc);
System.out.println(verifier.verify(sig)); // false

5Cipher: Keeping Data Secret

Cipher is the only one of the four that hides data. It encrypts plaintext into ciphertext and decrypts it back with the right key. For symmetric encryption we use AES in GCM mode, which also authenticates the data, so tampering is detected on decryption. For asymmetric encryption, RSA with OAEP padding encrypts small values such as a key, but bulk data is always encrypted with a symmetric key.

Java
Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
byte[] iv = new byte[12];
new SecureRandom().nextBytes(iv);
c.init(Cipher.ENCRYPT_MODE, aesKey, new GCMParameterSpec(128, iv));
byte[] ct = c.doFinal(plain); // plain.length + 16 bytes of tag
What each engine guarantees
ClassKeyGives usTypical use
MessageDigestnoneintegrity if hash is trustedchecksums, content ids
Macshared secretintegrity and origin among key holderswebhooks, signed cookies
Signatureprivate signs, public verifiesintegrity, origin, non-repudiationJWT RS256 or ES256, releases
Ciphersecret (or public for RSA-OAEP)confidentiality (plus integrity with GCM)encrypting fields, files

6When to Use SecureRandom

Every value an attacker must not guess comes from SecureRandom: keys, IVs and nonces, salts, session ids, password reset tokens, API keys. SecureRandom draws from the operating system's entropy source and produces output that cannot be predicted from earlier output.

java.util.Random is a linear congruential generator with a 48-bit state. From two consecutive outputs, an attacker can recover the state and predict every future value, which turns "random" reset tokens into guessable ones. It is fine for shuffling a quiz, never for security.

Java
Random weak = new Random(42);
System.out.println(weak.nextInt()); // -1170105035, the same on every JVM for seed 42
SecureRandom sr = new SecureRandom();
byte[] token = new byte[32];
sr.nextBytes(token); // 256 unpredictable bits

new SecureRandom() is the right default on modern JDKs. SecureRandom.getInstanceStrong() picks the strongest configured source but may block on some systems while waiting for entropy, so it is best kept for long-term keys.

7Follow-up questions

Why not just use SHA-256(secret + message) instead of HMAC?

With SHA-256 and similar hashes, that construction is vulnerable to length extension: an attacker can append data to the message and compute a valid hash without knowing the secret. HMAC was designed to prevent this, so we use Mac with HmacSHA256 rather than inventing our own.

Is encryption with AES enough to prevent tampering?

Only with an authenticated mode such as GCM. In older modes like CBC, an attacker can flip bits in the ciphertext and change the decrypted result without detection, and padding oracle attacks become possible. GCM adds a tag that makes decryption fail if anything changed.

8Conclusion

In this answer, we separated the four JCA engines by the question each one answers. MessageDigest gives a keyless fingerprint for integrity, Mac adds a shared secret so only key holders can create a valid tag, Signature lets a private key sign and anyone with the public key verify, and Cipher keeps data secret. We also saw why SecureRandom must generate keys, IVs, tokens and salts, since java.util.Random can be predicted from its output.

What to say in the interviewAbout 90 seconds aloud

Open with

The four classes answer different questions. MessageDigest computes a hash like SHA-256, a 32-byte fingerprint with no key. It tells me data has not changed, but only if I got the hash from a trusted place, because anyone can recompute it, and it is too fast for passwords.

Then, if they want more

Mac, for example HmacSHA256, mixes in a shared secret key, so only parties who hold the key can produce a valid tag. That is what payment webhooks use, and I compare tags with MessageDigest.isEqual so the comparison is constant time. The limit is that both sides have the same key, so it does not prove which one wrote the message.

Signature uses a key pair: the private key signs and anyone with the public key verifies, with RSA, ECDSA or Ed25519, which the JDK supports since Java 15. That is how JWTs with RS256 and certificates work, and it gives non-repudiation.

Cipher is the only one that hides data: it encrypts and decrypts, and for symmetric encryption I use AES in GCM mode, which also detects tampering.

For anything secret or unpredictable, keys, IVs, salts, session ids and reset tokens, I use SecureRandom, which gets its seed from the operating system. java.util.Random has only 48 bits of state and can be predicted from a couple of outputs, so it is fine for a game but never for security. On modern JDKs, new SecureRandom() is the right default.

About this answer

Last updated
12 November 2026
Versions it names
Java 15
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Spring Security reference
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Explain the difference between MessageDigest, Mac, Signature and Cipher in the Java...": https://scrivio-interview-library.netlify.app/spring-boot/secrets-and-crypto/d582202558/