rspec/rules/S3329/java/rule.adoc

73 lines
2.5 KiB
Plaintext

include::../description.adoc[]
== 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");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); // Noncompliant: the IV is hard coded and thus not generated with a secure random generator
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes("UTF-8"));
return DatatypeConverter.printBase64Binary(bytesIV)
+ ";" + 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");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); // Compliant
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes("UTF-8"));
return DatatypeConverter.printBase64Binary(bytesIV)
+ ";" + DatatypeConverter.printBase64Binary(encryptedBytes);
}
}
----
== See
* https://owasp.org/Top10/A02_2021-Cryptographic_Failures/[OWASP Top 10 2021 Category A2] - Cryptographic Failures
* https://www.owasp.org/index.php/Top_10-2017_A6-Security_Misconfiguration[OWASP Top 10 2017 Category A6] - Security Misconfiguration
* https://cwe.mitre.org/data/definitions/329.html[MITRE, CWE-329] - CWE-329: Not Using an Unpredictable IV with CBC Mode
* https://cwe.mitre.org/data/definitions/330.html[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
* Derived from FindSecBugs rule https://find-sec-bugs.github.io/bugs.htm#STATIC_IV[STATIC_IV]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::../message.adoc[]
'''
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]