Java Cipher getInstance()

In this guide, you will learn about the Cipher getInstance() method in Java programming and how to use it with an example.

1. Cipher getInstance() Method Overview

Definition:

The getInstance() method of the Cipher class in Java is used to create a new Cipher instance that implements the specified transformation. The transformation is a string in the form of "algorithm/mode/padding" or "algorithm". This method is part of the javax.crypto package and is fundamental for implementing encryption and decryption in Java.

Syntax:

public static final Cipher getInstance(String transformation) throws NoSuchAlgorithmException, NoSuchPaddingException

Parameters:

- transformation: a String, representing the transformation the returned Cipher object should implement.

Key Points:

- The getInstance() method throws a NoSuchAlgorithmException if the specified algorithm is unavailable.

- It also throws a NoSuchPaddingException if the specified padding mechanism is unavailable.

- The returned Cipher object needs to be initialized before it can be used.

- Common algorithms include "AES", "DES", "RSA", etc.

2. Cipher getInstance() Method Example

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class CipherExample {

    public static void main(String[] args) {
        try {
            // Specify the transformation
            String transformation = "AES/ECB/PKCS5Padding";

            // Create a key
            SecretKeySpec key = new SecretKeySpec("abcdefghijklmnop".getBytes(), "AES");

            // Get Cipher instance
            Cipher cipher = Cipher.getInstance(transformation);

            // Initialize the Cipher in encrypt mode
            cipher.init(Cipher.ENCRYPT_MODE, key);

            // Encrypt the data
            byte[] encryptedData = cipher.doFinal("Hello, World!".getBytes());

            // Encode the encrypted data to Base64
            String encodedData = Base64.getEncoder().encodeToString(encryptedData);

            // Print the encrypted data
            System.out.println("Encrypted Data: " + encodedData);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output:

Encrypted Data: zQY9zjTZl9yvmDf+KluNUQ==

Explanation:

In this example, the Cipher.getInstance() method is used to get a Cipher instance with the specified transformation "AES/ECB/PKCS5Padding". 

We have created a SecretKeySpec object as the key and initialized the Cipher object in encryption mode using cipher.init()

After initializing, we used the doFinal() method of the Cipher class to encrypt the input string "Hello, World!". The encrypted byte array is then encoded to a Base64 string and printed to the console.

Comments