Fixed initialization vectors

Fixed or reused initialization vectors

Description

AES-CBC needs an unpredictable IV for every encryption. AES-GCM needs an IV (nonce) that never repeats under the same key. A zero-filled array or a fixed string reuses the same IV.

Potential impact

With the same key and IV, CBC reveals identical first plaintext blocks. In GCM, reuse can expose relationships between messages and permit forged tags. Replay protection requires separate protocol controls.

Remediation

  • Use a 16-byte IV for AES-CBC and normally a 12-byte IV for GCM. Fill random IVs with SecureRandom.nextBytes(iv) and store or transmit the IV with the ciphertext.
  • Random IVs can collide. Limit encryptions per key and rotate keys. If you choose a misuse-resistant mode such as AES-GCM-SIV, continue to use distinct nonces under each key.

Examples

Before

java
import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class StaticIvBad {
    // BAD: 고정(제로) IV 사용으로 GCM 보안 붕괴
    public byte[] encrypt(byte[] key, byte[] plaintext) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
        SecretKeySpec sk = new SecretKeySpec(key, "AES");
        byte[] iv = new byte[12]; // 모든 바이트가 0 -> 예측 가능
        GCMParameterSpec spec = new GCMParameterSpec(128, iv);
        cipher.init(Cipher.ENCRYPT_MODE, sk, spec);
        return cipher.doFinal(plaintext);
    }
}

After

java
import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.ByteBuffer;
import java.security.SecureRandom;

public class RandomIvGood {
    // GOOD: 매번 SecureRandom으로 새 IV 생성하고, IV를 암호문과 함께 저장/전달
    public byte[] encrypt(byte[] key, byte[] plaintext) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
        SecretKeySpec sk = new SecretKeySpec(key, "AES");
        byte[] iv = new byte[12]; // GCM 권장 12바이트
        SecureRandom.getInstanceStrong().nextBytes(iv);
        GCMParameterSpec spec = new GCMParameterSpec(128, iv);
        cipher.init(Cipher.ENCRYPT_MODE, sk, spec);
        byte[] ciphertext = cipher.doFinal(plaintext);
        // IV || C 형식으로 결합해 저장/전달
        ByteBuffer out = ByteBuffer.allocate(iv.length + ciphertext.length);
        out.put(iv).put(ciphertext);
        return out.array();
    }
}

The example fills the 12-byte array with random bytes before initializing GCM. It returns the IV followed by the ciphertext and its 128-bit authentication tag.

References