Java Cryptography Basics
In this page:
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
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());
}
}
Login to try C/C++/Java/PHP code in the editor
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
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");
}
}
Login to try C/C++/Java/PHP code in the editor
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
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 cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] ciphertext = cipher.doFinal("secret data".getBytes());
System.out.println("Encrypted length: " + ciphertext.length);
}
}
Login to try C/C++/Java/PHP code in the editor
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
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));
}
}
Login to try C/C++/Java/PHP code in the editor
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
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());
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 19 topics to unlock
0/19 topics done
Complete these topics first:
- Java Reflection API
- Java Annotations Advanced
- Java Garbage Collection
- Java Memory Management
- Java Performance Optimization
- Java Advanced Interview Questions
- Java CompletableFuture
- Java Atomic Classes
- Java Locks & Semaphores
- Java Concurrent Collections
- Java Cryptography Basics
- Java Hashing (MD5, SHA)
- Java SSL & HTTPS
- Java Logging (Log4j/SLF4J)
- Java Serialization Advanced
- Java Interview Questions Advanced
- Java Connection Pooling
- Java Test Driven Development
- Java Integration Testing