Why is this an issue?
When encrypting data with the Cipher Block Chaining (CBC) mode an Initialization Vector (IV) is used to randomize the encryption, ie under a given
key the same plaintext doesn’t always produce the same ciphertext. The IV doesn’t need to be secret but should be unpredictable to avoid
"Chosen-Plaintext Attack".
To generate Initialization Vectors, NIST recommends to use a secure random number generator.
Noncompliant code example
public void encrypt(String key, String plainText) throws GeneralSecurityException {
byte[] bytesIV = "7cVgr5cbdCZVw5WY".getBytes(StandardCharsets.UTF_8); // secondary
GCMParameterSpec iv = new GCMParameterSpec(128,bytesIV); // secondary
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); // Noncompliant
}
Compliant solution
public void encrypt(String key, String plainText) throws GeneralSecurityException {
SecureRandom random = new SecureRandom();
byte[] bytesIV = new byte[16];
random.nextBytes(bytesIV); // Random initialization vector
GCMParameterSpec iv = new GCMParameterSpec(128, bytesIV);
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
}
Resources