AES 256 Encryption in Java

Security has become an important aspect nowadays. Java programming provides security for data transfer as well as communication between several nodes by supporting different encryption and hashing algorithms. In this section, we will discuss the AES 256 encryption algorithm and implement the logic in a Java program.

What is AES?

AES is an Advanced Encryption Standard algorithm. It is a type of symmetric, block cipher encryption and decryption algorithm. It works with key size 128, 192, and 256 bits. It uses a valid and similar secret key for both encryption and decryption.

In AES, the block cipher is used. It means that the data to be encrypted is converted into blocks for encryption. The original data value is encrypted using different bits of padding such as 128, 192, or 256 bits.

Advantages of AES

  • The encrypted data cannot be decrypted without a valid secret key.
  • AES is the most common security algorithm used worldwide for various purposes like wireless communication, financial transactions, encrypted data storage, etc.
  • The companies who want to transfer their data safely and without breaking it can always use the AES algorithm.
  • Disadvantages of AES

  • AES algorithm uses very simple algebraic formulae.
  • Each block is encrypted using a similar kind of encryption.
  • AES can be difficult to implement with the software.
  • AES 256 Encryption and Decryption

  • Using the AES encryption algorithm, a plain text message is converted into a cipher text with the help of a secret key that is only known to the sender and receiver of the message.
  • Encrypting or decrypting a message or a string is supported by Java Cryptographic Extension (JCE) framework in Java.
  • The Java Cryptographic Extension framework provides different packages for encryption and decryption.
  • java.security
  • java.security.cert
  • java.security.spec
  • java.security.interfaces
  • javax.crypto
  • javax.crypto.spec
  • javax.crypto.interfaces
  • While decrypting a message, the reverse process of encryption is followed. It requires the value of the secret key in order to acquire the original message.
  • The Cipher class in Java is used for the encryption and decryption process. The init() method of the Cipher class initializes the cipher using the public key from the given transformation type.
  • Modes of Operation of AES Algorithm

    There are the following six modes of operation in the AES algorithm:

    1. ECB (Electronic Code Book):

    It is the simplest mode among all. It divides the plaintext message into blocks of size 128 bits. Then these blocks are encrypted using the same key and algorithm. Hence, it generates the same cipher text for the same block every time. It is considered a weakness and therefore it is suggested not to use ECB for encryption.

    2. CBC (Cipher Block Chaining):

    CBC uses an Initialization Vector (IV) to improve the encryption. In CBC, the encryption is performed by XOR operation between the plaintext and IV. Then the cipher text is generated. It then uses the encryption result to XOR with the plain text until the last block.

    3. CFB (Cipher FeedBack):

    CFB can be used as a stream cipher . It encrypts the initialization vector (IV) first and then XOR with the plaintext to generate the cipher text. Then it encrypts the cipher text with the next plaintext block. In this mode, decryption can be performed in a parallel manner but encryption cannot be performed in a parallel manner.

    4. OFB (Output FeedBack):

    OFB can also be used as a stream cipher. It does not need padding data. First, the IV is encrypted and then the encryption result is XOR with the plaintext to generate the cipher text. Here, the IV cannot be encrypted or decrypted in a parallel manner.

    5. CTR (Counter):

    In CTR mode the encryption process is similar to OFB mode, the only difference is that it encrypts the counter value instead of IV.

    It has two advantages, encryption or decryption can be performed in a parallel manner and the noise of one block does not affect another block.

    6. GCM (Galois/Counter Mode):

    GCM mode is an extended version of CTR mode. It was introduced by NIST. The GCM mode provides the cipher text as well as authentication tag after the encryption process.

    In the following program, the AES/CBC/PKCS5Padding algorithm is used as it is popular and used in many projects.

    AES-256 Encryption and Decryption Java Program

    AESExample.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 AESExample /* Private variable declaration */ private static final String SECRET_KEY = "123456789"; private static final String SALTVALUE = "abcdefg"; /* Encryption Method */ public static String encrypt(String strToEncrypt) /* Declare a 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 factory for secret keys. */ SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); /* PBEKeySpec class implements KeySpec interface. */ KeySpec spec = new PBEKeySpec(SECRET_KEY.toCharArray(), SALTVALUE.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); /* Retruns encrypted value. */ return Base64.getEncoder() .encodeToString(cipher.doFinal(strToEncrypt.getBytes(StandardCharsets.UTF_8))); catch (InvalidAlgorithmParameterException | InvalidKeyException | NoSuchAlgorithmException | InvalidKeySpecException | BadPaddingException | IllegalBlockSizeException | NoSuchPaddingException e) System.out.println("Error occured during encryption: " + e.toString()); return null; /* Decryption Method */ public static String decrypt(String strToDecrypt) /* Declare a 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 factory for secret keys. */ SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); /* PBEKeySpec class implements KeySpec interface. */ KeySpec spec = new PBEKeySpec(SECRET_KEY.toCharArray(), SALTVALUE.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); /* Retruns decrypted value. */ return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt))); catch (InvalidAlgorithmParameterException | InvalidKeyException | NoSuchAlgorithmException | InvalidKeySpecException | BadPaddingException | IllegalBlockSizeException | NoSuchPaddingException e) System.out.println("Error occured during decryption: " + e.toString()); return null; /* Driver Code */ public static void main(String[] args) /* Message to be encrypted. */ String originalval = "AES Encryption"; /* Call the encrypt() method and store result of encryption. */ String encryptedval = encrypt(originalval); /* Call the decrypt() method and store result of decryption. */ String decryptedval = decrypt(encryptedval); /* Display the original message, encrypted message and decrypted message on the console. */ System.out.println("Original value: " + originalval); System.out.println("Encrypted value: " + encryptedval); System.out.println("Decrypted value: " + decryptedval);

    Output:

    Original value: AES Encryption Encrypted value: V5E9I52IxhMaW4+hJhl56g== Decrypted value: AES Encryption

    In the above Java program, the AESExample class defines two methods, encrypt() that implements the AES-256 encryption algorithm and decrypt() that implements the AES-256 decryption algorithm. And lastly, the driver method gives a call to both the methods and displays the result on the console.

    In this article, we have discussed the AES 256 encryption algorithm in Java, its modes of operations with its implementation as well as its pros and cons.

    Next Topic Applications of Array in Java