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
val bytesIV = "7cVgr5cbdCZVw5WY".toByteArray(charset("UTF-8")) // Predictable / hardcoded IV
val iv = IvParameterSpec(bytesIV)
val skeySpec = SecretKeySpec(secretKey.toByteArray(), "AES")
val cipher: Cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING")
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv) // Noncompliant (s3329)
val encryptedBytes: ByteArray = cipher.doFinal("foo".toByteArray())
Compliant solution
val random: SecureRandom = SecureRandom()
val bytesIV: ByteArray = ByteArray(16)
random.nextBytes(bytesIV); // Unpredictable / random IV
val iv = IvParameterSpec(bytesIV)
val skeySpec = SecretKeySpec(secretKey.toByteArray(), "AES")
val cipher: Cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING")
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv) //Compliant (s3329)
val encryptedBytes: ByteArray = cipher.doFinal("foo".toByteArray())
Resources