...
This rule falls under EX0 of rule FIO11-J. Do not attempt to read raw binary data as character data. Also, see the related rule IDS10-J. Do not assume every character in a string is the same size for more information.
Noncompliant Code Example
This noncompliant code example reads a byte array and converts it into a String
using the platform's default character encoding. When the default encoding differs from the encoding that was used to produce the byte array, the resulting String
is likely to be incorrect. Undefined behavior can occur when some of the input lacks a valid character representation in the default encoding.
Code Block | ||
---|---|---|
| ||
try { FileInputStream fis = new FileInputStream("SomeFile"); DataInputStream dis = new DataInputStream(fis); byte[] data = new byte[1024]; dis.readFully(data); String result = new String(data); } catch (IOException x) { // handle error } |
Compliant Solution
This compliant solution explicitly specifies the intended character encoding by passing it as the second argument to the String
constructor (e.g. the string encoding
in this example).
Code Block | ||
---|---|---|
| ||
try { FileInputStream fis = new FileInputStream("SomeFile"); DataInputStream dis = new DataInputStream(fis); byte[] data = new byte[1024]; dis.readFully(data); String encoding = "SomeEncoding"; // for example, "UTF-16LE" String result = new String(data, encoding); } catch (IOException x) { // handle error } |
Exceptions
IDS17-EX0: An explicit character encoding may be omitted on the receiving side when the data was produced by a Java application that uses the same platform and default character encoding.
Risk Assessment
Failure to specify the character encoding while performing file or network I/O can corrupt the data.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
IDS17-J | low | unlikely | medium | P2 | L3 |
Automated Detection
Sound automated detection of this vulnerability is not feasible.
Related Guidelines
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Bibliography
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="d0e46e695a824d8e-e8f3374c-43a94c91-9f7fb5c7-4f03fd9f2e6c552d04d83f87"><ac:plain-text-body><![CDATA[ | [[Encodings 2006 | AA. Bibliography#Encodings 06]] | ]]></ac:plain-text-body></ac:structured-macro> |
...