Cipher Block Chaining IV's should be unpredictable (java:S3329)

Hi All,

I have a use case where I’m encrypting in the JavaScript code and decrypting in the Java code using AES/CBC/PKCS5Padding algorithm.

I’m generating a random IV in the JavaScript code and sending along with the ciphertext, which I’m parsing in Java and passing to Decryption.

Sonarlint throws a vulnerability(java:S3329) since I’m not generating a random IV instead I’m using from the cipher text which i received from the Javascript code.


 String decryptedPassword = new String(Base64.getDecoder().decode(encryptedPassword));
            String iv = decryptedPassword.split("!!")[2];
            String salt = decryptedPassword.split("!!")[0];
            String cipherText = decryptedPassword.split("!!")[1];
            int keySize = 256;
            int iterationCount = 1000;
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");

            SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
            KeySpec spec = new PBEKeySpec(encryptionKey.toCharArray(), Hex.decodeHex(salt), iterationCount, keySize);
            SecretKey key = new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");
            
            IvParameterSpec ivParameterSpec = new IvParameterSpec(Hex.decodeHex(iv));
			
            cipher.init(Cipher.DECRYPT_MODE, key, ivParameterSpec);
            byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(cipherText));
            return new String(decrypted, StandardCharsets.UTF_8);

How to resolve this issue.

1 Like

Hi Melwin and welcome to the community!

By random chance I just answered this some minutes ago in another thread. Lucky me, now I can just copy my answer:

Your code looks indeed fine. The IV should only be randomly generated when encrypting but of course for the decrypting part that is not possible, since it has to match the IV that was used for encrypting.

In some cases it is not easily possible for us to determine if the code will encrypt or decrypt but in this case it should be no problem. I have created the ticket SONARJAVA-4122 to fix the issue. Thanks for the report!

1 Like

Thanks Hendrik :slightly_smiling_face:

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.