|
| 1 | +package checks.security; |
| 2 | + |
| 3 | +import java.security.InvalidAlgorithmParameterException; |
| 4 | +import java.security.InvalidKeyException; |
| 5 | +import java.security.SecureRandom; |
| 6 | +import javax.crypto.Cipher; |
| 7 | +import javax.crypto.spec.IvParameterSpec; |
| 8 | +import javax.crypto.spec.SecretKeySpec; |
| 9 | + |
| 10 | +import static javax.crypto.Cipher.ENCRYPT_MODE; |
| 11 | + |
| 12 | +public class CipherBlockChainingCheckShouldDetectCustomIVFactories { |
| 13 | + private static final SecureRandom SECURE_RANDOM = new SecureRandom(); |
| 14 | + |
| 15 | + // We use fields to omit the details of cipher and secret key creation because they are not relevant for this test. |
| 16 | + static Cipher cipher; |
| 17 | + static SecretKeySpec secretKey; |
| 18 | + |
| 19 | + static class Control { |
| 20 | + void should_raise_issue_for_insecure_iv() throws InvalidAlgorithmParameterException, InvalidKeyException { |
| 21 | + final byte[] insecureIv = new byte[42]; |
| 22 | + cipher.init(ENCRYPT_MODE, secretKey, new IvParameterSpec(insecureIv)); // Noncompliant |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + void should_not_raise_if_iv_generator_does_not_return_byte_array_01() throws InvalidAlgorithmParameterException, InvalidKeyException { |
| 27 | + final byte[] iv = returnsNothing(); |
| 28 | + // This code is non-compiling and the called iv generator is not recognized as secure because it has the wrong return type. |
| 29 | + // We accept possible FPs in such cases: |
| 30 | + cipher.init(ENCRYPT_MODE, secretKey, new IvParameterSpec(iv)); // Noncompliant |
| 31 | + } |
| 32 | + |
| 33 | + void should_not_raise_if_iv_generator_does_not_return_byte_array_02() throws InvalidAlgorithmParameterException, InvalidKeyException { |
| 34 | + final byte[] iv = returnsIntArray(42); |
| 35 | + // This code is non-compiling and the called iv generator is not recognized as secure because it has the wrong return type. |
| 36 | + // We accept possible FPs in such cases: |
| 37 | + cipher.init(ENCRYPT_MODE, secretKey, new IvParameterSpec(iv)); // Noncompliant |
| 38 | + } |
| 39 | + |
| 40 | + private void returnsNothing() { |
| 41 | + } |
| 42 | + |
| 43 | + private int[] returnsIntArray(final int length) { |
| 44 | + return new int[length]; |
| 45 | + } |
| 46 | +} |
0 commit comments