2023-05-03 11:06:20 +02:00
== Why is this an issue?
2021-06-08 14:23:48 +02:00
When CBC (Cypher Block Chaining) is used for encryption, the IV (Initialization Vector) must be random an unpredictable. Otherwise it exposes the encrypted value to crypto-analysis attacks like "Chosen-Plaintext Attacks".
An IV should be used in one and only one encryption cycle because its purpose is to ensure that a different cyphertext value results each time a given plain text value is encrypted.
2023-05-03 11:06:20 +02:00
=== Noncompliant code example
2021-06-08 14:23:48 +02:00
2022-02-04 17:28:24 +01:00
[source,text]
2021-06-08 14:23:48 +02:00
----
public String cbcEncrypt(String strKey, String plainText) {
String strIV = "7cVgr5cbdCZVw5WY";
IvParameterSpec ivSpec = new IvParameterSpec(strIV.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(strKey.getBytes("UTF-8"), "AES");
/* Ciphering */
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivSpec); // Noncompliant
byte[] encryptedBytes = cipher.doFinal(plaintText.getBytes("UTF-8"));
return DatatypeConverter.printBase64Binary(ivBytes) + ";" + DatatypeConverter.printBase64Binary(encryptedBytes);
}
----
2023-05-03 11:06:20 +02:00
=== Compliant solution
2021-06-08 14:23:48 +02:00
2022-02-04 17:28:24 +01:00
[source,text]
2021-06-08 14:23:48 +02:00
----
private SecureRandom random = new SecureRandom();
public void cbcEncrypt(String strKey, String plainText) {
byte ivBytes[] = new byte[16];
random.nextBytes(ivBytes);
IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
SecretKeySpec skeySpec = new SecretKeySpec(strKey.getBytes("UTF-8"), "AES");
/* Ciphering */
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivSpec);
byte[] encryptedBytes = cipher.doFinal(plaintText.getBytes("UTF-8"));
return DatatypeConverter.printBase64Binary(ivBytes) + ";" + DatatypeConverter.printBase64Binary(encryptedBytes);
}
----
2023-05-03 11:06:20 +02:00
== Resources
2021-06-08 14:23:48 +02:00
2021-11-01 15:00:32 +01:00
* https://owasp.org/Top10/A02_2021-Cryptographic_Failures/[OWASP Top 10 2021 Category A2] - Cryptographic Failures
2022-04-07 08:53:59 -05:00
* https://cwe.mitre.org/data/definitions/329[MITRE, CWE-329] - Not Using a Random IV with CBC Mode
2021-06-08 14:23:48 +02:00
* OWASP Top 10 2017 Category A6 - Security Misconfiguration