Skip to content
Related Articles

Related Articles

Improve Article

What is Java AES Encryption and Decryption?

  • Last Updated : 12 Apr, 2021

Java has introduced a new approach in the technology sector as a programming language. Java takes the top spot of technologies used for coding. A Java application design firm can do everything from comprehensive business software to apps for mobile phones and wireless devices. Omnipresent of this Software support is always there to get embedded through functioning methods and has been incorporated into common internet browsers. It implies that a similar key is utilized for both encryption and decoding. The (AES) is a generally utilized key encryption calculation.

Securing data transfer is done in multiple ways. But most experts refer to data encryption as the best method and currently, Java AES is an advanced solution available for ciphering. New algorithms are replacing the old values of DES towards the AES. It has a better legacy of confidential properties, data authentication, and high levels of integrity.

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

Let’s get cracking towards the decryption as well as on the encryption with a single key. It is a huge advantage over other methods to secure sensitive information. It is the best solution for government agencies and financial institutions which require protecting sensitive information.

Popularity of Symmetric Encryption Standard



As cybersecurity concerns arise, the use of AES as an advanced method strikes as the best alternative as it has 3 blocks cipher. They can scramble the 128-bit block with cryptographic keys. Both the sender and receiver possess the same key in order to keep information classified and secretive. This makes it a flexible and safe tool. It works in a block mode which is fixed or stream mode which uses bits of data. Currently, the applications are common for email communications, TLS, and also instant messaging.

Choose the Right Padding Scheme for AES

In the block cipher mode, the plain text is converted into block size for encrypting. Here padding is required and Java provides 3 alternatives. For encoding, the AES algorithm is repetitive in nature and supports 128, 192, and 256 bits.

It functions like the below pattern.

Creating-Encryption-and-Decryption-with-Java-AES

  1. Electronic codebook
  2. Cipher blocking chain
  3. Cipher feedback
  4. Output feedback
  5. Counter
  6. Galois/Counter Mode

The choice of the key is required to future-proof the application.

Java




// Java program to demonstrate the creation
// of Encryption and Decryption with Java AES
import java.nio.charset.StandardCharsets;
import java.security.spec.KeySpec;
import java.util.Base64;
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;
  
class AES {
    // Class private variables
    private static final String SECRET_KEY
        = "my_super_secret_key_ho_ho_ho";
    
    private static final String SALT = "ssshhhhhhhhhhh!!!!";
  
    // This method use to encrypt to string
    public static String encrypt(String strToEncrypt)
    {
        try {
  
            // Create default byte array
            byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0,
                          0, 0, 0, 0, 0, 0, 0, 0 };
            IvParameterSpec ivspec
                = new IvParameterSpec(iv);
  
            // Create SecretKeyFactory object
            SecretKeyFactory factory
                = SecretKeyFactory.getInstance(
                    "PBKDF2WithHmacSHA256");
            
            // Create KeySpec object and assign with
            // constructor
            KeySpec spec = new PBEKeySpec(
                SECRET_KEY.toCharArray(), SALT.getBytes(),
                65536, 256);
            SecretKey tmp = factory.generateSecret(spec);
            SecretKeySpec secretKey = new SecretKeySpec(
                tmp.getEncoded(), "AES");
  
            Cipher cipher = Cipher.getInstance(
                "AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey,
                        ivspec);
            // Return encrypted string
            return Base64.getEncoder().encodeToString(
                cipher.doFinal(strToEncrypt.getBytes(
                    StandardCharsets.UTF_8)));
        }
        catch (Exception e) {
            System.out.println("Error while encrypting: "
                               + e.toString());
        }
        return null;
    }
  
    // This method use to decrypt to string
    public static String decrypt(String strToDecrypt)
    {
        try {
  
            // Default byte array
            byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0,
                          0, 0, 0, 0, 0, 0, 0, 0 };
            // Create IvParameterSpec object and assign with
            // constructor
            IvParameterSpec ivspec
                = new IvParameterSpec(iv);
  
            // Create SecretKeyFactory Object
            SecretKeyFactory factory
                = SecretKeyFactory.getInstance(
                    "PBKDF2WithHmacSHA256");
  
            // Create KeySpec object and assign with
            // constructor
            KeySpec spec = new PBEKeySpec(
                SECRET_KEY.toCharArray(), SALT.getBytes(),
                65536, 256);
            SecretKey tmp = factory.generateSecret(spec);
            SecretKeySpec secretKey = new SecretKeySpec(
                tmp.getEncoded(), "AES");
  
            Cipher cipher = Cipher.getInstance(
                "AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, secretKey,
                        ivspec);
            // Return decrypted string
            return new String(cipher.doFinal(
                Base64.getDecoder().decode(strToDecrypt)));
        }
        catch (Exception e) {
            System.out.println("Error while decrypting: "
                               + e.toString());
        }
        return null;
    }
}
  
// driver code
public class Main {
    public static void main(String[] args)
    {
        // Create String variables
        String originalString = "GeeksforGeeks";
        
        // Call encryption method
        String encryptedString
            = AES.encrypt(originalString);
        
        // Call decryption method
        String decryptedString
            = AES.decrypt(encryptedString);
  
        // Print all strings
        System.out.println(originalString);
        System.out.println(encryptedString);
        System.out.println(decryptedString);
    }
}
Output
GeeksforGeeks
LuBu3DTLx7SLfjfhbjl7lw==
GeeksforGeeks

If there is no proper padding to the block, then the system shows errors of the password. It is also important to do security testing before the Java AES is allowed to work. AES uses input data, secret key, and IV.IV. The secret key is generated via a random number or is password-driven. For security best practices this system works the best. It is important to understand the AES 256 encryption to use mathematical codes for sensitive data.

Advantages of AES

  • It allows the data to remain secure until it is revealed by a secret key.
  • Many enterprises can now use it to keep hackers away from scrambling the information.
  • For agencies that require data in an unbreakable format ad also transmitted safely, it is the most flexible and viable option.

The earliest AES was approved for National Security Agency, USA. Its speed turned out to be most useful along with the same secret key for sender and receiver and how long it is. The block cipher continues to be the star performer for the substitution-permutation combination. It also has additional security with round keys which require multiple modifications. Each stage/level of encryption performs an important function. Longer the key and more rounds ensure high performance. 




My Personal Notes arrow_drop_up
Recommended Articles
Page :