How to encrypt and decrypt strings in Java using the Cipher class, secret keys, Base64 encoding, and symmetric algorithms.
In this JavaAnt guide, we cover how to encrypt and decrypt strings in Java using the standard Cipher class from the javax.crypto package.
Core Concepts
The Cipher class is part of the Java Cryptographic Extension (JCE) framework:
- Encryption:
cleartext + secret key + algorithm = ciphertext - Decryption:
ciphertext + secret key + algorithm = cleartext
Symmetric vs Asymmetric
- Symmetric: The same secret key is used for both encryption and decryption (e.g., AES, DES).
- Asymmetric: A public/private key pair is used. Encryption is performed with the public key, and decryption with the private key (e.g., RSA).
Block vs Stream Ciphers
- Block Cipher: Processes data in discrete blocks (e.g., 128-bit blocks).
- Stream Cipher: Processes incoming data unit by unit (byte or bit).
Common Transformations
AES/CBC/PKCS5Padding(128, 192, 256 bits)AES/GCM/NoPadding(authenticated encryption, recommended in modern Java)
Implementation
package com.javaant;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class CipherUtils {
private static final byte[] KEY = {
0x24, 0x68, 0x78, 0x71, 0x49, 0x73, 0x41, 0x24,
0x28, 0x78, 0x41, 0x49, 0x63, 0x41, 0x73, 0x09
};
public static String encrypt(String strToEncrypt) {
try {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
SecretKeySpec secretKey = new SecretKeySpec(KEY, "AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return Base64.encodeBase64String(cipher.doFinal(strToEncrypt.getBytes()));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String decrypt(String strToDecrypt) {
try {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
SecretKeySpec secretKey = new SecretKeySpec(KEY, "AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return new String(cipher.doFinal(Base64.decodeBase64(strToDecrypt)));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}package com.javaant;
public class EncryptionDecryption {
public static void main(String[] args) {
String original = "Confidential Payload";
String encrypted = CipherUtils.encrypt(original);
String decrypted = CipherUtils.decrypt(encrypted);
System.out.println("Encrypted: " + encrypted);
System.out.println("Decrypted: " + decrypted);
}
}For file encryption using RSA, see our RSA file encryption tutorial. For modern authenticated encryption with AES-GCM, see the AES encryption tutorial.