== How to fix it in Java Cryptography Extension === Code examples ==== Noncompliant code example [source,java,diff-id=1,diff-type=noncompliant] ---- import java.nio.charset.StandardCharsets; import java.security.NoSuchAlgorithmException; import java.security.InvalidKeyException; import java.security.InvalidAlgorithmParameterException; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import javax.crypto.NoSuchPaddingException; public void encrypt(String key, String plainText) { byte[] RandomBytes = "7cVgr5cbdCZVw5WY".getBytes(StandardCharsets.UTF_8); IvParameterSpec iv = new IvParameterSpec(RandomBytes); SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES"); try { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv); } catch(NoSuchAlgorithmException|InvalidKeyException| NoSuchPaddingException|InvalidAlgorithmParameterException e) { // ... } } ---- ==== Compliant solution :explicit_strong: java.security.SecureRandom include::../../common/fix/explicit-fix.adoc[] [source,java,diff-id=1,diff-type=compliant] ---- import java.nio.charset.StandardCharsets; import java.security.SecureRandom; import java.security.NoSuchAlgorithmException; import java.security.InvalidKeyException; import java.security.InvalidAlgorithmParameterException; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import javax.crypto.NoSuchPaddingException; public void encrypt(String key, String plainText) { SecureRandom random = new SecureRandom(); byte[] randomBytes = new byte[128]; random.nextBytes(randomBytes); IvParameterSpec iv = new IvParameterSpec(randomBytes); SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES"); try { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv); } catch(NoSuchAlgorithmException|InvalidKeyException| NoSuchPaddingException|InvalidAlgorithmParameterException e) { // ... } } ---- === How does this work? include::../../common/fix/fix.adoc[]