← Back to Advanced Java Course | Chapter 11: Advanced & Security | Lesson 11 of 19

Java Cryptography Basics

Cryptography is scrambling information so only the right person can read it, like a secret code with a key. Java has tools to make keys, lock messages and unlock them.

Cryptography Overview

The Java Cryptography Architecture (JCA) provides a standard, pluggable set of classes and provider interfaces for encrypting and decrypting sensitive data, letting your application code stay the same even if the underlying cryptographic algorithm implementation changes.

Example: Cryptography Overview

java
import javax.crypto.Cipher;
public class Main {
	public static void main(String[] args) throws Exception {
		Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); // pluggable provider, same code regardless of implementation
		System.out.println(cipher.getAlgorithm());
	}
}

Generating Keys

The KeyGenerator class produces secure, cryptographically random keys for symmetric encryption algorithms like AES. Using a proper KeyGenerator instead of a hand-rolled random source matters, since weak or predictable keys undermine the security of even a strong encryption algorithm.

Example: Generating Keys

java
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
public class Main {
	public static void main(String[] args) throws Exception {
		KeyGenerator keyGen = KeyGenerator.getInstance("AES");
		keyGen.init(128);
		SecretKey key = keyGen.generateKey(); // cryptographically random, not hand-rolled
		System.out.println(key.getAlgorithm() + " key generated");
	}
}

Symmetric Encryption with AES

To encrypt data with AES, you initialize a Cipher object in ENCRYPT_MODE with your secret key, then call doFinal() on your plaintext byte array to get back the ciphertext -- the same key and mode pairing is required on the decrypting side to reverse the process.

Example: Symmetric Encryption with AES

java
// Import javax.crypto.* so it can be used by its short name
import javax.crypto.*;
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) throws Exception {
		KeyGenerator keyGen = KeyGenerator.getInstance("AES");
		keyGen.init(128);
		SecretKey key = keyGen.generateKey();
		Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
		cipher.init(Cipher.ENCRYPT_MODE, key);
		byte[] ciphertext = cipher.doFinal("secret data".getBytes());
		// Print a line to the console
		System.out.println("Encrypted length: " + ciphertext.length);
	}
}

Symmetric Decryption with AES

To decrypt AES-encrypted data, you initialize the Cipher object in DECRYPT_MODE using the exact same secret key that was used to encrypt it, then call doFinal() on the encrypted byte array to recover the original plaintext bytes.

Example: Symmetric Decryption with AES

java
import javax.crypto.*;
public class Main {
	public static void main(String[] args) throws Exception {
		KeyGenerator keyGen = KeyGenerator.getInstance("AES");
		keyGen.init(128);
		SecretKey key = keyGen.generateKey();
		Cipher encryptCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
		encryptCipher.init(Cipher.ENCRYPT_MODE, key);
		byte[] ciphertext = encryptCipher.doFinal("secret data".getBytes());
		Cipher decryptCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
		decryptCipher.init(Cipher.DECRYPT_MODE, key); // same key, DECRYPT_MODE
		byte[] plaintext = decryptCipher.doFinal(ciphertext);
		System.out.println(new String(plaintext));
	}
}

Cipher Modes and Padding

Always specify explicit cipher modes and padding schemes (like 'AES/GCM/NoPadding') rather than relying on a JCA provider's default settings, since some historically default combinations (such as ECB mode) have known weaknesses that can leak information about the plaintext.

Example: Cipher Modes and Padding

java
import javax.crypto.*;
public class Main {
	public static void main(String[] args) throws Exception {
		Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); // explicit mode, not a weak default like ECB
		System.out.println(cipher.getAlgorithm());
	}
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using Cipher.getInstance("AES"), which defaults to ECB mode and is not secure; specify a mode such as AES/GCM/NoPadding.
  2. Reusing the same IV (nonce) with the same key in GCM, which breaks its security.
  3. Not saving the IV together with the ciphertext, so the data cannot be decrypted later.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.