Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Wiki Markup
Every Java platform has a default character encoding. The available encodings are listed in the Supported Encodings document \[[Encodings 2006|AA. Bibliography#Encodings 06]\]. The default encoding is used when a character is converted to a sequence of bytes and _vice versa_. IfWhen characters are converted into an array of bytes to be sent as output, transmitted across some medium, input and converted back into characters, then the same encoding must be used on both sides of the conversation.

...

This noncompliant code example reads a byte array and converts it into a String using the platform's default character encoding for the platform. If this is not the same encoding as the one . When the default encoding differs from the encoding that was used to produce the byte array, the resulting String is likely to be incomprehensible because incorrect. Undefined behavior can occur when some of the bytes may not have input lacks a valid character representations representation in the default encoding.

Code Block
bgColor#FFCCCC
FileInputStream fis = new FileInputStream("SomeFile");
DataInputStream dis = new DataInputStream(fis);
int bytesRead = 0;
byte[] data = new byte[1024];

bytesRead = dis.readFully(data);

if (bytesRead > 0) {
  String result = new String(data);
}

...

This compliant solution explicitly specifies the intended character encoding by passing the string encoding it as the second argument to the String constructor (e.g. the string encoding in this example).

Code Block
bgColor#CCCCFF
String encoding = "SomeEncoding" // for example, "UTF-16LE"

FileInputStream fis = new FileInputStream("SomeFile");
DataInputStream dis = new DataInputStream(fis);
int bytesRead = 0;
byte[] data = new byte[1024];

bytesRead = dis.readFully(data);

if (bytesRead > 0) {
   String result = new String(data, encoding);
}

Exceptions

FIO03-EX1: If the data is coming from An explicit character encoding may be omitted on the receiving side when the data was created by another Java application that both uses the same platform and it is known that the application is using the default character encoding, an explicit character encoding is not required to be specified on the receiving sideand also uses the default character encoding.

Risk Assessment

Failure to specify the character encoding while performing file or network IO can corrupt the data.

Guideline

Severity

Likelihood

Remediation Cost

Priority

Level

FIO03-J

low

unlikely

medium

P2

L3

Automated Detection

TODOSound automated detection of this vulnerability is not feasible.

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this guideline on the CERT website.

...