×

AES 256 Encryption in Java

Now a days, security has grown in importance. Java programming supports a variety of encryption and hashing methods, which offers security for data transport and communication among various nodes. In this part, we'll talk about the AES 256 encryption technique and show how to use the logic in a Java program.

What does AES mean?

AES is known as the Advanced Encryption Standard algorithm. It is a form of symmetric encryption and decryption algorithm for block ciphers. It functions with keys of 128, 192, and 256 bits in size. It uses a legitimate secret key comparable for encryption and decryption.

The block cypher is employed in AES. It implies that the data that has to be encrypted is divided up into blocks. In order to encrypt the original data value, different padding bits, such as 128, 192, or 256 bits, are used.

AES Algorithm

The AES technique uses iterative, symmetric-key block cyphers that let cryptographic keys (secret keys) of 128, 192, and 256 bits to encrypt and decode data in blocks of 128 bits. If the 128-bit block size requirement is not reached, the data that has to be encrypted must be padded. Padding is accomplished by including 128 bits in the final block.

Java's Java Cryptographic Extension (JCE) architecture supports the encryption and decryption of messages and strings.

For encryption and decryption, the Java Cryptographic Extension framework offers a variety of packages.

1. java. security

2. java.security.cert

3. java.security.spec

4. java.security.interfaces

5. javax.crypto

6. javax. crypto.spec

7. javax. crypto.interfaces

Java's Cipher class is utilized for both encryption and decoding. The opposite process of encryption is used when decrypting a communication. To obtain the original message, it needs the value of the secret key. The public key from the specified transformation type is used to initialize the cypher using the init() function of the Cipher class.

AES Algorithm Operation Modes

1. ECB

2. CBC

3. CFB

4. OF

5. CTR

6. GCM

Electronic Code Book

It is the most basic option available. The plaintext message is divided into blocks of 128 bits in size. The same technique and key are then used to encrypt these blocks. As a result, it consistently produces the same cypher text for the same block. It is advised not to utilize ECB for encryption since it is considered a vulnerability.

Cipher Block Chaining

CBC uses an Initialization Vector (IV) to enhance the encryption. When using CBC, the plaintext and IV are XORed to encrypt the data. The encryption text is then produced. The plain text and encryption results are then XORed until the last block.

Cipher FeedBack

A stream cypher can be created using CFB. The cypher text is created by encrypting the initialization vector (IV) and then XORing it with the plaintext. The next plaintext block is then used to encrypt the cypher text. In this mode, decryption and encryption can be done simultaneously, but not the other way around.

Output Feedback

OFB can also be applied as a stream cypher. There is no need for padding information. The cypher text is created by first encrypting the IV and then XORing the encrypted result with plaintext. The IV cannot be simultaneously encrypted or decrypted in this situation.

CTR

Except for encrypting the counter value rather than the IV, the encryption procedure in CTR mode is identical to that in OFB mode. It has two benefits: encryption and decryption may be done simultaneously, and the noise of one block doesn't impact that of another.

Galois/Counter Mode

An expanded variant of CTR mode is GCM mode. NIST first introduced it. After the encryption procedure, the GCM mode offers the cypher text and authentication tag.

Program For AES-256 Encryption and Decryption in java

AESEncryptionDecryption.java

import javax.crypto.Cipher; 
import javax.crypto.SecretKey; 
import javax.crypto.SecretKeyFactory; 
import javax.crypto.spec.IvParameterSpec; 
import javax.crypto.spec.PBEKeySpec; 
import javax.crypto.spec.SecretKeySpec; 
import java.nio.charset.StandardCharsets; 
import java.security.InvalidAlgorithmParameterException; 
import java.security.InvalidKeyException; 
import java.security.NoSuchAlgorithmException; 
import java.security.spec.InvalidKeySpecException; 
import java.security.spec.KeySpec; 
import java.util.Base64; 
import javax.crypto.BadPaddingException; 
import javax.crypto.IllegalBlockSizeException; 
import javax.crypto.NoSuchPaddingException; 
public class AESEncryptionDecryption 
{ 
/* Private variable declaration */ 
private static final String secret_key = "R12346789"; 
private static final String Value_Salt = "!@#$%^&*()"; 
/* Method for Encryption */ 
public static String encrypt(String strToEncrypt) 
{ 
try 
{ 
/* Establish a byte array. */ 
byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; 
IvParameterSpec is = new IvParameterSpec(iv); 
/* Making a hidden key factory. */ 
SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); 
/* The PBEKeySpec class implements the KeySpec interface. */ 
KeySpec s1 = new PBEKeySpec(secret_key.toCharArray(), Value_Salt.getBytes(), 65536, 256); 
SecretKey t1 = f.generateSecret(s1); 
SecretKeySpec SK = new SecretKeySpec(t1.getEncoded(), "AES"); 
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 
cipher.init(Cipher.ENCRYPT_MODE, sk, is); 
/* the encrypted value is returned */ 
return Base64.getEncoder() 
.encodeToString(cipher.doFinal(strToEncrypt.getBytes(StandardCharsets.UTF_8))); 
} 
catch (InvalidAlgorithmParameterException | InvalidKeyException | NoSuchAlgorithmException | InvalidKeySpecException | BadPaddingException | IllegalBlockSizeException | NoSuchPaddingException e) 
{ 
System.out.println("Error while encryption: " + e.toString()); 
} 
return null; 
} 
/* Method for Decryption */ 
public static String decrypt(String strToDecrypt) 
{ 
try 
{ 
/* Establish a byte array. */ 
byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; 
IvParameterSpec is = new IvParameterSpec(iv); 
/* Making a hidden key factory. */ 
SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); 
/* The PBEKeySpec class implements the KeySpec interface. */ 
KeySpec s1 = new PBEKeySpec(secret_key.toCharArray(), Value_Salt.getBytes(), 65536, 256); 
SecretKey t1 = f.generateSecret(s1); 
SecretKeySpec SK = new SecretKeySpec(t1.getEncoded(), "AES"); 
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); 
cipher.init(Cipher.DECRYPT_MODE, sk, is); 
/* the encrypted value is returned */ 
return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt))); 
} 
catch (InvalidAlgorithmParameterException | InvalidKeyException | NoSuchAlgorithmException | InvalidKeySpecException | BadPaddingException | IllegalBlockSizeException | NoSuchPaddingException e) 
{ 
System.out.println("Error while decryption: " + e.toString()); 
} 
return null; 
} 
public static void main(String[] args) 
{ 
/* Encrypting the message.*/ 
String original_value = "AES 256 Encryption and Decryption"; 
/* Invoke the encrypt() function, then save the result. */ 
String encrypted_value = encrypt(original_value); 
/* Use the decrypt() function and then save the decryption results. */ 
String decrypted_value = decrypt(encrypted_value); 
System.out.println("Original value: " + original_value); 
System.out.println("Encrypted value: " + encrypted_value); 
System.out.println("Decrypted value: " + decrypted_value); 
} 
} 

Output

AES 256 Encryption in Java

Related Topics

For Loop Program in Java

For Loop Program in Java The for-loop program in Java is written when we want a particular set of statements to be executed repeatedly until the given criteria/ condition is met....

8 minutes read.

Display List of TimeZone with GMT and UTC in Java

It is vital to establish the right TimeZone in Java code when working with dates for Daylight Saving Time. In this part, we will present the time zones with GMT. TimeZone Those...

5 minutes read.

Enterprise Java Beans

One of the many Java APIs for the common development of corporate software is Enterprise Java Beans (EJB). An EJB, a server-side software component, contains the business logic of an...

4 minutes read.

Java Integer floatValue() method

The floatValue() method of Integer class returns a float value for this Integer after a widening primitive conversion. Syntax public float floatValue() Parameters NA Specified by This method is specified by floatValue in class Number Return Value This...

1 minute read.

Deque in Java

Deque in java collections with Example Deque is short for “double-ended queue.” It is a linear collection that extends the Queue interface and supports insertion and deletion of the element at both the...

3 minutes read.

Java Queue Interface

Queue interface is a subtype of Collection interface. All methods in the Collection interface are also available in the Queue interface. It provides operations of Collection and also some additional...

2 minutes read.

How to Return Value from Lambda Expression Java?

What is Lambda Expression in Java? In Java 8, Lambda Expressions were introduced.A lambda expression is a brief section of code that accepts input and outputs a value. Similar to methods,...

4 minutes read.

Zigzag Array in Java

In this tutorial, we discuss, what is zigzag array and its example. Even we will create the java program. In this program, we convert the simple array into a zigzag...

4 minutes read.

How to get the current date and time in Java

Introduction: In this article, we are going to discover many processes for Getting the existing-day Date and Time in Java. Most programs require timestamping events or showing date/times, among many...

3 minutes read.

Maximum length of string in java

In java, String can act as a data type and a class. The string can be defined as the collection of characters that are enclosed with double quotes(“ “). The...

3 minutes read.

Java Integer sum() method

The sum() method of Java Integer class add the two specified integers values. It returns the same result as given by + operator. Syntax public static int sum (int a, int b)  Parameters The...

1 minute read.

Java Final Keyword

In Java, the last keyword is used to limit the user. The applications of the java final keyword have large range of usage in program development. Last can be: variablemethodclass A final...

3 minutes read.

Java 9 Tutorial

The Java 9 is most popular release of java programming to make it platform modular. It is used to improve JDK and java implementation security. It provides JAVA SE and...

3 minutes read.

Powerful Number in Java

We will define a powerful number in this article and write Java programs to determine whether a given number is a powerful number or not. Java coding interviews and academic...

6 minutes read.

How to Convert boolean to String in Java

How to Convert boolean to String in Java There are two methods to convert boolean to String. Using valueOf(boolean) method Using toString(boolean) method For both the above methods, if the passes Boolean...

2 minutes read.

Java Generate Random String

Java Generate Random String In this tutorial, we will learn about to generate random string in Java. Random generation strings mean any string will be generated, which does not follow any...

7 minutes read.

How to Split the String in Java with Delimiter

In Java, splitting strings is a significant and typically used activity while coding. Java gives different ways of dividing the String. The most widely recognized way is to use the...

3 minutes read.

Java Return Keyword

The return keyword in Java is used to end a method's execution. the caller receives the return, followed by the appropriate value. The return type of the method, such as...

3 minutes read.

Encapsulation Program in Java

Encapsulation Program in Java Encapsulation program in Java demonstrates the technique to bind methods and fields in a single unit. The term encapsulation is inspired by the word ‘capsule’, which is...

3 minutes read.

Java Integer compare() method

The compare() method of Integer class compares the two specified int values. Syntax public static int compare(int x, int y) Parameters The parameters ‘x’ and ‘y’ represent the first and second int values to...

2 minutes read.