🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
In this tutorial, we will learn about how to use Cipher class, which provides cryptographic encryption and decryption functionality in Java.
Java Cipher class overview
The Java Cipher (javax.crypto.Cipher) class represents an encryption algorithm. The term Cipher is a standard term for an encryption algorithm in the world of cryptography.
You can use a Cipher instance to encrypt and decrypt data in Java. Read more about Cipher class in JavaDoc.
Creating a Cipher object
Before you can use a Java Cipher you just create an instance of the Cipher class. You create a Cipher instance by calling its getInstance() method with a parameter telling what type of encryption algorithm you want to use.
Here is an example of creating a Java Cipher instance:
Cipher cipher = Cipher.getInstance("AES");
This example creates a Cipher instance using the encryption algorithm called AES.
Cipher Modes
Some encryption algorithms can work in different modes. An encryption mode specifies details about how the algorithm should encrypt data. Thus, the encryption mode impacts part of the encryption algorithm.
Here are some of the most well-known cipher modes:
- ECB - Electronic Codebook
- CBC - Cipher Block Chaining
- CFB - Cipher Feedback
- OFB - Output Feedback
- CTR - Counter
When instantiating a cipher you can append its mode to the name of the encryption algorithm.
For instance, to create an AES Cipher instance using Cipher Block Chaining (CBC) you use this code:
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
Initializing a Cipher
Before you can use a Cipher instance you must initialize it. Initializing a Cipher is done by calling its init() method. The init() method takes two parameters:
- Encryption / decryption cipher operation mode.
- Encryption / decryption key.
Here is an example of initializing a Cipher instance in encryption mode:
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
SecretKey secretKey = new SecretKeySpec(keyBytes, ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
Here is an example of initializing a Cipher instance in decryption mode:
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
SecretKey secretKey = new SecretKeySpec(keyBytes, ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
Encrypting and Decrypting Data Example
After initializing the Cipher object, we call the doFinal() method to perform the encryption or decryption operation. This method returns a byte array containing the encrypted or decrypted message.
Here is the complete Java program to encrypt and decrypt the string:
package net.javaguides.examples.security;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
/**
*
* @author Ramesh Fadatare
*
*/
public class JavaCipherClassDemo {
private static final String ALGORITHM = "AES";
private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";
public String encryptMessage(byte[] message, byte[] keyBytes) throws InvalidKeyException, NoSuchPaddingException,
NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException {
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
SecretKey secretKey = new SecretKeySpec(keyBytes, ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedMessage = cipher.doFinal(message);
return new String(encryptedMessage);
}
public String decryptMessage(byte[] encryptedMessage, byte[] keyBytes) throws NoSuchPaddingException,
NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
SecretKey secretKey = new SecretKeySpec(keyBytes, ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] clearMessage = cipher.doFinal(encryptedMessage);
return new String(clearMessage);
}
public static void main(String[] args) throws InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException,
BadPaddingException, IllegalBlockSizeException {
String encKeyString = "1234567890123456";
String message = "Java Guides";
JavaCipherClassDemo cipherClassDemo = new JavaCipherClassDemo();
String encryptedstr = cipherClassDemo.encryptMessage(message.getBytes(), encKeyString.getBytes());
String decryptedStr = cipherClassDemo.decryptMessage(encryptedstr.getBytes(), encKeyString.getBytes());
System.out.println("Original String -> " + message);
System.out.println("Encrypted String -> " + encryptedstr);
System.out.println("Decrypted String -> " + decryptedStr);
}
}
Output:
Original String -> Java Guides
Encrypted String -> øgY};Ù’}±Ýë00®H³
Decrypted String -> Java Guides
References
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
🆕 High-Demand
80–90% OFF
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
🆕 High-Demand
80–90% OFF
ChatGPT + Generative AI + Prompt Engineering for Beginners
🚀 Trending Now
80–90% OFF
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
🌟 Top Rated
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
🌟 Top Rated
80–90% OFF
Testing Spring Boot Application with JUnit and Mockito
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Master Spring Data JPA with Hibernate
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
🎓 Student Favorite
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Comments
Post a Comment
Leave Comment