Implementing AES Encryption with Initialization Vectors in Java

AES (Advanced Encryption Standard) is a symmetric encryption algoirthm widely used for securing data. To enhance encryption randomness and strength, an Initialization Vector (IV) is often introducde. The following example demonstrates how to implement AES encryption with an IV using Java's Cipher class.

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

public class AESCipherUtil {
    public static byte[] encryptData(byte[] plainText, String secretKey, String ivString) throws Exception {
        SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(ivString.getBytes(StandardCharsets.UTF_8));
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
        return cipher.doFinal(plainText);
    }
}

The encryptData method takes the plaintext bytes, a secret key, and an IV string as inputs. It constructs a SecretKeySpec for the AES key, an IvParameterSpec for the initialization vector, and initializes the Cipher instance in encryption mode with the CBC transformation and PKCS5 padding. The IV ensures that identical plaintext blocks produce different ciphertext blocks, improving resistance against pattern analysis.

Tags: java AES Encryption Initialization Vector Symmetric Cryptography Security

Posted on Tue, 25 Aug 2026 16:53:33 +0000 by thecard