2021-04-26 17:29:13 +02:00
|
|
|
include::../description.adoc[]
|
2020-06-30 12:48:39 +02:00
|
|
|
|
|
|
|
== Noncompliant Code Example
|
|
|
|
|
|
|
|
----
|
|
|
|
public class MyCbcClass {
|
|
|
|
|
|
|
|
public String applyCBC(String strKey, String plainText) {
|
|
|
|
byte[] bytesIV = "7cVgr5cbdCZVw5WY".getBytes("UTF-8");
|
|
|
|
|
|
|
|
/* KEY + IV setting */
|
|
|
|
IvParameterSpec iv = new IvParameterSpec(bytesIV);
|
|
|
|
SecretKeySpec skeySpec = new SecretKeySpec(strKey.getBytes("UTF-8"), "AES");
|
|
|
|
|
|
|
|
/* Ciphering */
|
|
|
|
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
|
2021-04-26 17:29:13 +02:00
|
|
|
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); // Noncompliant: the IV is hard coded and thus not generated with a secure random generator
|
2020-06-30 12:48:39 +02:00
|
|
|
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes("UTF-8"));
|
2021-04-26 17:29:13 +02:00
|
|
|
return DatatypeConverter.printBase64Binary(bytesIV)
|
2020-06-30 12:48:39 +02:00
|
|
|
+ ";" + DatatypeConverter.printBase64Binary(encryptedBytes);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
----
|
|
|
|
|
|
|
|
== Compliant Solution
|
|
|
|
|
|
|
|
----
|
|
|
|
public class MyCbcClass {
|
|
|
|
|
|
|
|
SecureRandom random = new SecureRandom();
|
|
|
|
|
|
|
|
public String applyCBC(String strKey, String plainText) {
|
|
|
|
byte[] bytesIV = new byte[16];
|
|
|
|
random.nextBytes(bytesIV);
|
|
|
|
|
|
|
|
/* KEY + IV setting */
|
|
|
|
IvParameterSpec iv = new IvParameterSpec(bytesIV);
|
|
|
|
SecretKeySpec skeySpec = new SecretKeySpec(strKey.getBytes("UTF-8"), "AES");
|
|
|
|
|
|
|
|
/* Ciphering */
|
|
|
|
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
|
2021-04-26 17:29:13 +02:00
|
|
|
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); // Compliant
|
2020-06-30 12:48:39 +02:00
|
|
|
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes("UTF-8"));
|
|
|
|
return DatatypeConverter.printBase64Binary(bytesIV)
|
|
|
|
+ ";" + DatatypeConverter.printBase64Binary(encryptedBytes);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
----
|
|
|
|
|
|
|
|
== See
|
|
|
|
|
2021-04-26 17:29:13 +02:00
|
|
|
* https://www.owasp.org/index.php/Top_10-2017_A6-Security_Misconfiguration[OWASP Top 10 2017 Category A6] - Security Misconfiguration
|
|
|
|
* http://cwe.mitre.org/data/definitions/329[MITRE, CWE-329] - CWE-329: Not Using an Unpredictable IV with CBC Mode
|
|
|
|
* http://cwe.mitre.org/data/definitions/330[MITRE, CWE-330] - Use of Insufficiently Random Values
|
|
|
|
* https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38a.pdf[NIST, SP-800-38A] - Recommendation for Block Cipher Modes of Operation
|
2020-06-30 12:48:39 +02:00
|
|
|
* Derived from FindSecBugs rule https://find-sec-bugs.github.io/bugs.htm#STATIC_IV[STATIC_IV]
|
2021-06-02 20:44:38 +02:00
|
|
|
|
|
|
|
ifdef::rspecator-view[]
|
|
|
|
== Comments And Links
|
|
|
|
(visible only on this page)
|
|
|
|
|
|
|
|
include::../comments-and-links.adoc[]
|
|
|
|
endif::rspecator-view[]
|