Cryptography and secure randomness
What you will learn
Cryptographic primitives protect different properties. A digest summarizes bytes, a MAC authenticates bytes using a shared secret, a signature authenticates bytes using a private/public key pair, and authenticated encryption protects confidentiality and integrity. Java selects vetted algorithms through JCA and JCE providers; do not design your own cipher or use a general-purpose random generator for secrets.
- Choose a digest, MAC, signature or authenticated cipher for a defined need.
- Generate synthetic keys and random bytes without printing secrets.
- Reject changed ciphertext or associated data before using plaintext.
Each example is a complete Main.java file. Use a fresh lab-owned directory: javac --release 21 -proc:none Main.java, then java Main. Use only generated test keys and fixed synthetic inputs. Never supply real credentials or arbitrary serialized data. The runner enforces a process deadline.
Random bytes and a known SHA-256 digest
import java.io.*;import java.nio.charset.StandardCharsets;import java.security.*;import java.util.*;import javax.crypto.*;import javax.crypto.spec.GCMParameterSpec;import javax.net.ssl.*;public class Main {
public static void main(String[] args) throws Exception { byte[] token = new byte[32]; new SecureRandom().nextBytes(token); System.out.println(token.length); byte[] digest = MessageDigest.getInstance("SHA-256").digest("abc".getBytes(StandardCharsets.UTF_8)); System.out.println(HexFormat.of().formatHex(digest)); }}Expected output:
32ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015adThe generated token is never printed. The public input abc has a stable digest; the token itself is intentionally unpredictable.
Providers, randomness and digest
The Java Cryptography Architecture selects an implementation using a named algorithm and an installed provider. Provider availability and policy depend on the JDK and environment; fail closed if a required algorithm is unavailable. SecureRandom supplies cryptographic randomness; do not manually seed it with a timestamp or predictable value. The first example checks byte length rather than exact random output. SHA-256 hashes bytes, not abstract characters: specify UTF-8. A digest alone does not establish who produced the data; an attacker able to replace both payload and digest can compute another digest.
MACs and signatures
Use HmacSHA256 when trusted parties share a secret. Anyone with that key can generate tags, so it cannot identify an individual signer. Use a signature such as Ed25519 when verification must use a public key; the verifier still needs a trusted association between public key and identity. Verify the exact canonical bytes and authenticate context, version and identity as required by the protocol. Use separate keys for different purposes; avoid exposing generated keys or tags in logs. Reject failed verification before acting.
Authenticated encryption and key lifecycle
AES/GCM/NoPadding is an authenticated encryption transformation. A nonce is public but must never repeat under the same key; the small lab performs one encryption per generated key. In production enforce nonce uniqueness and key usage limits with a reviewed design, including across processes and restarts. Additional authenticated data (AAD) binds unencrypted context to the ciphertext; it must match during decryption. Retain the nonce, algorithm version, key identifier and ciphertext/tag; do not treat the toy mutable array record as a production envelope format. Do not release plaintext before authentication succeeds. Use a vetted key management service or protected keystore, separate keys by purpose, rotate with versioned identifiers and controlled migration, and never log secrets. Do not share mutable Cipher or Mac instances across threads without a documented safe strategy.
Passwords are a different problem
Do not store plaintext, encrypted passwords or raw SHA-256 digests as password verifiers. Use a maintained password-hashing library supporting a suitable adaptive salted scheme such as Argon2id, with reviewed memory/time cost, per-password salts, upgrade policy and rate limiting. Store encoded algorithm parameters and verifier, never the original password. External password hashing is conceptual here; no credential processing is executed.
Authenticate a synthetic message
import java.io.*;import java.nio.charset.StandardCharsets;import java.security.*;import java.util.*;import javax.crypto.*;import javax.crypto.spec.GCMParameterSpec;import javax.net.ssl.*;public class Main { static byte[] authenticate(SecretKey key, String message) throws GeneralSecurityException { Mac mac = Mac.getInstance("HmacSHA256"); mac.init(key); return mac.doFinal(message.getBytes(StandardCharsets.UTF_8)); } public static void main(String[] args) throws Exception { KeyGenerator keys = KeyGenerator.getInstance("HmacSHA256"); keys.init(256); SecretKey key = keys.generateKey(); byte[] tag = authenticate(key, "stock:3"); System.out.println(MessageDigest.isEqual(tag, authenticate(key, "stock:3"))); System.out.println(MessageDigest.isEqual(tag, authenticate(key, "stock:4"))); }}Expected output:
truefalseChanging the message invalidates the original tag. The symmetric key is generated in memory and discarded.
Verify a signed release label
import java.io.*;import java.nio.charset.StandardCharsets;import java.security.*;import java.util.*;import javax.crypto.*;import javax.crypto.spec.GCMParameterSpec;import javax.net.ssl.*;public class Main { static boolean verify(PublicKey key, String message, byte[] signed) throws GeneralSecurityException { Signature verifier = Signature.getInstance("Ed25519"); verifier.initVerify(key); verifier.update(message.getBytes(StandardCharsets.UTF_8)); return verifier.verify(signed); } public static void main(String[] args) throws Exception { KeyPair pair = KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); Signature signer = Signature.getInstance("Ed25519"); signer.initSign(pair.getPrivate()); signer.update("release:7".getBytes(StandardCharsets.UTF_8)); byte[] signed = signer.sign(); System.out.println(verify(pair.getPublic(), "release:7", signed)); System.out.println(verify(pair.getPublic(), "release:8", signed)); }}Expected output:
truefalseThe public key verifies the original bytes, not changed bytes. Trust in that public key is a separate requirement.
Encrypt and authenticate contextual data
import java.io.*;import java.nio.charset.StandardCharsets;import java.security.*;import java.util.*;import javax.crypto.*;import javax.crypto.spec.GCMParameterSpec;import javax.net.ssl.*;public class Main { record Envelope(byte[] nonce, byte[] ciphertext) {} static SecretKey newKey() throws GeneralSecurityException { KeyGenerator keys = KeyGenerator.getInstance("AES"); keys.init(128); return keys.generateKey(); } static Envelope seal(SecretKey key, String text, String context) throws GeneralSecurityException { byte[] nonce = new byte[12]; new SecureRandom().nextBytes(nonce); Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); cipher.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(128, nonce)); cipher.updateAAD(context.getBytes(StandardCharsets.UTF_8)); return new Envelope(nonce, cipher.doFinal(text.getBytes(StandardCharsets.UTF_8))); } static String open(SecretKey key, Envelope envelope, String context) throws GeneralSecurityException { Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); cipher.init(Cipher.DECRYPT_MODE, key, new GCMParameterSpec(128, envelope.nonce())); cipher.updateAAD(context.getBytes(StandardCharsets.UTF_8)); return new String(cipher.doFinal(envelope.ciphertext()), StandardCharsets.UTF_8); } public static void main(String[] args) throws Exception { SecretKey key = newKey(); Envelope envelope = seal(key, "stock:3", "warehouse:v1"); System.out.println(open(key, envelope, "warehouse:v1")); try { open(key, envelope, "warehouse:v2"); throw new AssertionError("wrong context accepted"); } catch (AEADBadTagException expected) { System.out.println("rejected"); } }}Expected output:
stock:3rejectedThe expected context opens the ciphertext; changed AAD fails authentication. No random bytes or secret keys appear in the output.
Common mistakes
Avoid Random for secrets, provider-default AES modes, repeated GCM nonces, comparing secret tags with ordinary String equality, raw password hashes, or trusting a signature merely because it verifies under an arbitrary supplied public key. Never catch an authentication failure and continue with plaintext.
Practice
Generate a fresh AES key and seal the text stock:5 with context warehouse:v1. Open it with the correct context. Then change one ciphertext byte and require AEADBadTagException without displaying unauthenticated data.
Expected output:
stock:5rejectedCompare your answer with the manual practice criteria.
Official reading: SecureRandom · MessageDigest · Mac · Signature · Cipher · KeyGenerator · GCMParameterSpec · Password storage. Java 25 execution remains unverified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Cryptography and secure randomness — knowledge check
Original Java security questions.
Which primitive authenticates data with a shared key?
Which property must a GCM nonce have?
Why use UTF-8 explicitly?
What does a valid signature establish?
What is suitable for password storage?