Java Cipher Class Example Tutorial - Encryption and Decryption Example

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


Comments