Versions Compared

Key

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

...

In this noncompliant code example, a byte array is read and converted into a string using the default character encoding for the platform. If this is not the same encoding as was used to produce the byte array then the resulting string will be garbage because the some of the bytes may not have valid character representations in the default encoding.

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

bytesRead = fisdis.readreadFully(data);

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

...

Code Block
bgColorCCCCFF
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 = fisdis.readreadFully(data);

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

Exceptions

*EX1:* If the data is coming from another Java application on the same platform and it is known that that application is using the default character encoding, then an explicit character encoding does not need to be specified on the receiving side.

Risk Assessment

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

FIO03-J

low

unlikely

medium

P1

L2

Other Languages

A related rule appears in the C Secure Coding Standard as MSC10-C. Character Encoding - UTF8 Related Issues

...

Automated Detection

TODO

Related Vulnerabilities

...