Java Cryptography Basics
Java cryptography lets you protect data so that others cannot read it, change it without being noticed, or pretend to be someone else. The JDK includes everything you need for the common tasks: hashing, message authentication codes (HMAC), encryption and digital signatures.
This lesson explains each building block in plain terms and shows how to use it with the standard java.security and javax.crypto APIs. It ends with a real-world example that encrypts notes with a password using PBKDF2 and AES-GCM. If you have not read it yet, Java Security explains how providers and getInstance work.
Java Cryptography Terms You Need to Know
| Term | Meaning |
|---|---|
| Plaintext | The original readable data |
| Ciphertext | The scrambled data after encryption |
| Key | Secret value that controls encryption, decryption or signing |
| IV / nonce | Random value used once per encryption so equal messages encrypt differently |
| Hash | Fixed-size fingerprint of data; cannot be reversed |
| MAC | Hash that also needs a secret key; proves data was not changed |
| Digital signature | Created with a private key, checked with a public key; proves who sent the data |
The building blocks solve different problems, so the first step is always to pick the right one.
| Goal | Building block | Java class | Algorithm to use |
|---|---|---|---|
| Detect accidental changes | Hash | MessageDigest | SHA-256 |
| Detect deliberate changes (shared key) | MAC | Mac | HmacSHA256 |
| Keep data secret | Symmetric encryption | Cipher | AES/GCM/NoPadding |
| Prove who created data | Digital signature | Signature | Ed25519 or ECDSA |
| Turn a password into a key | Key derivation | SecretKeyFactory | PBKDF2WithHmacSHA256 |
Encoding Is Not Encryption
Base64 turns bytes into printable text. It is useful for storing and sending binary data, but it hides nothing, because anyone can decode it without a key.
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class Base64NotEncryption {
public static void main(String[] args) {
String apiKey = "sk-live-12345";
String encoded = Base64.getEncoder().encodeToString(apiKey.getBytes(StandardCharsets.UTF_8));
System.out.println("Encoded: " + encoded);
// Anyone can reverse Base64 without any key
String decoded = new String(Base64.getDecoder().decode(encoded), StandardCharsets.UTF_8);
System.out.println("Decoded: " + decoded);
}
}
Output:
Encoded: c2stbGl2ZS0xMjM0NQ==
Decoded: sk-live-12345
How it works:
Base64.getEncoder()converts the bytes of the key to text using 64 safe characters.Base64.getDecoder()reverses it immediately. There is no secret involved, so Base64 offers no protection.
Note: You will still use Base64 in almost every crypto program. Keys, ciphertext and signatures are raw bytes, and Base64 is how you store them in a text file, a database column or a JSON field.
Hashing Data With SHA-256
A cryptographic hash turns any amount of data into a fixed-size value. The same input always gives the same hash, but a tiny change gives a completely different one, and you cannot get the input back from the hash.
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HexFormat;
public class HashingExample {
static String sha256Hex(String text) throws Exception {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(text.getBytes(StandardCharsets.UTF_8));
return HexFormat.of().formatHex(hash);
}
public static void main(String[] args) throws Exception {
System.out.println(sha256Hex("Pay Ravi 500"));
System.out.println(sha256Hex("Pay Ravi 500")); // same input -> same hash
System.out.println(sha256Hex("Pay Ravi 900")); // one character changed -> completely different
System.out.println("Length: " + sha256Hex("any text at all, short or very long").length() + " hex chars (256 bits)");
}
}
Output:
8e7ba99fefbd1bbae8aa57a0e7bf945d0cdaba487eb6ac325764c53d60029783
8e7ba99fefbd1bbae8aa57a0e7bf945d0cdaba487eb6ac325764c53d60029783
a47e0df8f614ea0738e865dfca3cd29a21cb6f62b03f2674eb5412df3f03db10
Length: 64 hex chars (256 bits)
How it works:
MessageDigest.getInstance("SHA-256")gets a SHA-256 implementation, anddigestreturns 32 bytes.- The first two lines are identical, so a hash works as a fingerprint for checking downloads or detecting duplicate files.
- Changing
500to900changes the whole hash. This "avalanche effect" makes it impossible to adjust data to match a chosen hash.
Note: A plain hash only detects accidental changes. An attacker who changes the message can simply compute a new hash. For passwords, use a slow salted hash as shown in Java Password Hashing.
Message Authentication With HMAC
An HMAC combines a hash with a secret key. Only someone who has the key can produce the correct tag, so the receiver knows the message really came from a key holder and was not changed. Payment gateways and webhooks use HMAC signatures for exactly this.
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HexFormat;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class HmacExample {
static byte[] hmac(byte[] key, String message) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(key, "HmacSHA256"));
return mac.doFinal(message.getBytes(StandardCharsets.UTF_8));
}
public static void main(String[] args) throws Exception {
// A fixed demo key; real keys come from a KeyGenerator or a secrets store
byte[] sharedKey = "demo-key-shared-by-server-and-app".getBytes(StandardCharsets.UTF_8);
String message = "order=1042&amount=1499";
byte[] tag = hmac(sharedKey, message);
System.out.println("Message: " + message);
System.out.println("HMAC : " + HexFormat.of().formatHex(tag));
// The receiver recomputes the tag and compares in constant time
System.out.println("Original verifies? " + MessageDigest.isEqual(tag, hmac(sharedKey, message)));
System.out.println("Tampered verifies? " + MessageDigest.isEqual(tag, hmac(sharedKey, "order=1042&amount=1")));
byte[] wrongKey = "attacker-guess".getBytes(StandardCharsets.UTF_8);
System.out.println("Wrong key verifies? " + MessageDigest.isEqual(tag, hmac(wrongKey, message)));
}
}
Output:
Message: order=1042&amount=1499
HMAC : fc74284c6d5c8d399712ab3f42a2b7af218c2212deb9a64dd2db217830646531
Original verifies? true
Tampered verifies? false
Wrong key verifies? false
How it works:
SecretKeySpecwraps the raw key bytes, andMac.initloads the key into the HMAC engine.doFinalreturns a 32-byte tag for the message. The sender sends the message and the tag together.- The receiver computes the tag again with its own copy of the key. A changed amount or a wrong key gives a different tag.
MessageDigest.isEqualcompares the tags in constant time, which avoids timing attacks.
Encrypting Data With AES-GCM in Java
AES is the standard symmetric cipher: the same key encrypts and decrypts. Always use it in GCM mode, which encrypts the data and adds an authentication tag, so any change to the ciphertext is detected during decryption.
| Setting | Value | Why |
|---|---|---|
| Transformation | AES/GCM/NoPadding | Authenticated encryption; GCM needs no padding |
| Key size | 256 bits | Strong and fast on modern CPUs |
| IV | 12 random bytes, new for every message | Reusing an IV with the same key breaks GCM |
| Tag length | 128 bits | Full-strength integrity check |
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import javax.crypto.AEADBadTagException;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
public class AesGcmExample {
private static final int IV_BYTES = 12; // 96-bit nonce, the standard size for GCM
private static final int TAG_BITS = 128; // authentication tag size
public static void main(String[] args) throws Exception {
// 1. Create a random 256-bit AES key
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(256);
SecretKey key = keyGenerator.generateKey();
// 2. Create a fresh random IV for this message
byte[] iv = new byte[IV_BYTES];
new SecureRandom().nextBytes(iv);
// 3. Encrypt
String plaintext = "Student marks: Asha=91, Ravi=84";
Cipher encryptCipher = Cipher.getInstance("AES/GCM/NoPadding");
encryptCipher.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(TAG_BITS, iv));
byte[] ciphertext = encryptCipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
System.out.println("Plaintext bytes : " + plaintext.length());
System.out.println("Ciphertext bytes: " + ciphertext.length + " (data + 16-byte tag)");
// 4. Decrypt with the same key and IV
Cipher decryptCipher = Cipher.getInstance("AES/GCM/NoPadding");
decryptCipher.init(Cipher.DECRYPT_MODE, key, new GCMParameterSpec(TAG_BITS, iv));
System.out.println("Decrypted: " + new String(decryptCipher.doFinal(ciphertext), StandardCharsets.UTF_8));
// 5. Change one bit of the ciphertext: GCM detects it
ciphertext[5] ^= 1;
try {
decryptCipher.init(Cipher.DECRYPT_MODE, key, new GCMParameterSpec(TAG_BITS, iv));
decryptCipher.doFinal(ciphertext);
} catch (AEADBadTagException e) {
System.out.println("Tampering detected: " + e.getMessage());
}
}
}
Output:
Plaintext bytes : 31
Ciphertext bytes: 47 (data + 16-byte tag)
Decrypted: Student marks: Asha=91, Ravi=84
Tampering detected: Tag mismatch
How it works:
KeyGeneratorcreates a random 256-bit AES key. In a real application you would store it in a key store or a secrets manager.SecureRandomfills a new 12-byte IV. The IV is not secret; it is stored or sent next to the ciphertext.Cipher.getInstance("AES/GCM/NoPadding")andinit(ENCRYPT_MODE, ...)prepare encryption. The ciphertext is the plaintext length plus a 16-byte tag.- Decryption uses the same key and IV and returns the original text.
- Flipping a single bit makes
doFinalthrowAEADBadTagException. GCM never returns tampered data.
Note: Never use
Cipher.getInstance("AES")without a mode. The JDK then usesAES/ECB/PKCS5Padding, and ECB mode encrypts equal blocks to equal output, which leaks patterns in your data.
Digital Signatures With Ed25519
Asymmetric cryptography uses a key pair. The private key is kept secret and creates signatures; the public key can be shared with everyone and only verifies them. This lets anyone check that a document came from you without being able to fake your signature.
import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
public class SignatureExample {
static byte[] sign(PrivateKey privateKey, String document) throws Exception {
Signature signer = Signature.getInstance("Ed25519");
signer.initSign(privateKey);
signer.update(document.getBytes(StandardCharsets.UTF_8));
return signer.sign();
}
static boolean verify(PublicKey publicKey, String document, byte[] signature) throws Exception {
Signature verifier = Signature.getInstance("Ed25519");
verifier.initVerify(publicKey);
verifier.update(document.getBytes(StandardCharsets.UTF_8));
return verifier.verify(signature);
}
public static void main(String[] args) throws Exception {
// GOCOURSE signs certificates with its private key
KeyPair gocourseKeys = KeyPairGenerator.getInstance("Ed25519").generateKeyPair();
String certificate = "Certificate: Asha completed Java Security";
byte[] signature = sign(gocourseKeys.getPrivate(), certificate);
System.out.println("Signature size: " + signature.length + " bytes");
System.out.println("Public key algorithm: " + gocourseKeys.getPublic().getAlgorithm());
// Anyone with the public key can check it
System.out.println("Genuine certificate valid? " + verify(gocourseKeys.getPublic(), certificate, signature));
System.out.println("Edited certificate valid? "
+ verify(gocourseKeys.getPublic(), "Certificate: Ravi completed Java Security", signature));
// A signature from someone else's key does not verify
KeyPair fakeKeys = KeyPairGenerator.getInstance("Ed25519").generateKeyPair();
byte[] forged = sign(fakeKeys.getPrivate(), certificate);
System.out.println("Forged signature valid? " + verify(gocourseKeys.getPublic(), certificate, forged));
}
}
Output:
Signature size: 64 bytes
Public key algorithm: EdDSA
Genuine certificate valid? true
Edited certificate valid? false
Forged signature valid? false
How it works:
KeyPairGenerator.getInstance("Ed25519")(Java 15+) creates a modern elliptic-curve key pair.getAlgorithm()reports the family name,EdDSA.signuses the private key. Ed25519 signatures are always 64 bytes.verifyuses only the public key. Changing the name in the certificate makes verification fail.- A signature made with a different private key fails too, so nobody can issue fake certificates without GOCOURSE's private key.
Note: Signatures do not hide the data; the certificate text is still readable. If you need both secrecy and proof of origin, encrypt the data and sign it.
Real-World Example: Password-Protected Secret Notes
This example encrypts a note with a password the user remembers. The password is turned into an AES key with PBKDF2, the note is encrypted with AES-GCM, and the salt, IV and ciphertext are packed into one Base64 token that can be saved anywhere.
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.AEADBadTagException;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
public class SecretNotes {
private static final byte VERSION = 1;
private static final int SALT_BYTES = 16;
private static final int IV_BYTES = 12;
private static final int TAG_BITS = 128;
private static final int ITERATIONS = 600_000;
private static final SecureRandom RANDOM = new SecureRandom();
// Turn a password into a 256-bit AES key
private static SecretKey deriveKey(char[] password, byte[] salt) throws Exception {
PBEKeySpec spec = new PBEKeySpec(password, salt, ITERATIONS, 256);
try {
byte[] keyBytes = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(spec).getEncoded();
return new SecretKeySpec(keyBytes, "AES");
} finally {
spec.clearPassword();
}
}
// Output layout: version(1) | salt(16) | iv(12) | ciphertext+tag
static String encrypt(String note, char[] password) throws Exception {
byte[] salt = new byte[SALT_BYTES];
byte[] iv = new byte[IV_BYTES];
RANDOM.nextBytes(salt);
RANDOM.nextBytes(iv);
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, deriveKey(password, salt), new GCMParameterSpec(TAG_BITS, iv));
cipher.updateAAD(new byte[] {VERSION}); // the header is authenticated too
byte[] ciphertext = cipher.doFinal(note.getBytes(StandardCharsets.UTF_8));
ByteBuffer packed = ByteBuffer.allocate(1 + SALT_BYTES + IV_BYTES + ciphertext.length);
packed.put(VERSION).put(salt).put(iv).put(ciphertext);
return Base64.getEncoder().encodeToString(packed.array());
}
static String decrypt(String token, char[] password) throws Exception {
ByteBuffer packed = ByteBuffer.wrap(Base64.getDecoder().decode(token));
byte version = packed.get();
if (version != VERSION) {
throw new IllegalArgumentException("Unsupported format version " + version);
}
byte[] salt = new byte[SALT_BYTES];
byte[] iv = new byte[IV_BYTES];
packed.get(salt).get(iv);
byte[] ciphertext = new byte[packed.remaining()];
packed.get(ciphertext);
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, deriveKey(password, salt), new GCMParameterSpec(TAG_BITS, iv));
cipher.updateAAD(new byte[] {version});
return new String(cipher.doFinal(ciphertext), StandardCharsets.UTF_8);
}
public static void main(String[] args) throws Exception {
char[] password = "Masala-Dosa-Sunday".toCharArray();
String note = "Wi-Fi password for the lab: GoCourse@2026";
String token = encrypt(note, password);
System.out.println("Token length: " + token.length() + " chars (Base64)");
System.out.println("Same note encrypted twice, same token? " + token.equals(encrypt(note, password)));
System.out.println("Decrypted: " + decrypt(token, password));
try {
decrypt(token, "masala-dosa-sunday".toCharArray());
} catch (AEADBadTagException e) {
System.out.println("Wrong password: decryption refused");
}
byte[] damaged = Base64.getDecoder().decode(token);
damaged[damaged.length - 1] ^= 1;
try {
decrypt(Base64.getEncoder().encodeToString(damaged), password);
} catch (AEADBadTagException e) {
System.out.println("Damaged token: decryption refused");
}
Arrays.fill(password, '\0');
}
}
Output:
Token length: 116 chars (Base64)
Same note encrypted twice, same token? false
Decrypted: Wi-Fi password for the lab: GoCourse@2026
Wrong password: decryption refused
Damaged token: decryption refused
How it works:
- Key derivation. A password is not a key.
deriveKeyruns PBKDF2 with a random salt and 600,000 iterations to produce 32 key bytes, the same technique used for password hashing. - Fresh salt and IV. Every call to
encryptcreates a new salt and IV, so encrypting the same note twice gives two different tokens. - Authenticated header.
updateAADadds the version byte to the GCM tag without encrypting it. If someone changes the version, decryption fails, and the version lets you change the format safely later. - Packing.
ByteBufferwrites the version (1 byte), salt (16), IV (12) and ciphertext with tag into one array, and Base64 turns it into text. Decryption reads the parts back in the same order. - Wrong password or damage. A password with a different letter case produces a different key, and a flipped bit changes the ciphertext. In both cases GCM's tag check fails with
AEADBadTagException, so the program never shows wrong or tampered text. - Clean up. The password
char[]is wiped at the end, andclearPassword()wipes the copy insidePBEKeySpec.
Note: Java 25 added a standard Key Derivation Function API (
javax.crypto.KDF, JEP 510) with HKDF support. HKDF derives several keys from one strong secret, such as a shared TLS secret. For keys made from human passwords, a slow function such as PBKDF2 or Argon2 is still the right choice.