rspec/rules/S4425/java/rule.adoc

51 lines
1.5 KiB
Plaintext
Raw Normal View History

2021-04-28 16:49:39 +02:00
Using ``++Integer.toHexString++`` is a common mistake when converting sequences of bytes into hexadecimal string representations. The problem is that the method trims leading zeroes, which can lead to wrong conversions. For instance a two bytes value of ``++0x4508++`` would be converted into ``++45++`` and ``++8++`` which once concatenated would give ``++0x458++``.
This is particularly damaging when converting hash-codes and could lead to a security vulnerability.
This rule raises an issue when ``++Integer.toHexString++`` is used in any kind of string concatenations.
2021-04-28 16:49:39 +02:00
== Noncompliant Code Example
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] bytes = md.digest(password.getBytes("UTF-8"));
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(Integer.toHexString( b & 0xFF )); // Noncompliant
}
----
2021-04-28 16:49:39 +02:00
== Compliant Solution
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] bytes = md.digest(password.getBytes("UTF-8"));
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(String.format("%02X", b));
}
----
2021-04-28 16:49:39 +02:00
== See
2021-10-28 10:07:16 +02:00
* https://cwe.mitre.org/data/definitions/704.html[MITRE, CWE-704] - Incorrect Type Conversion or Cast
2021-04-28 16:49:39 +02:00
* Derived from FindSecBugs rule https://find-sec-bugs.github.io/bugs.htm#BAD_HEXA_CONVERSION[BAD_HEXA_CONVERSION]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::message.adoc[]
endif::env-github,rspecator-view[]