You are viewing an old version of this page. View the current version.

Compare with Current View Page History

Version 1 Next »

Every Java platform has a default character encoding. The codings available are listed in [[Encodings 06]]. The default encoding is used when a character is converted to a sequence of bytes and vice versa. If characters are being converted into an array of bytes, output, transmitted across some medium, input, and converted back into characters then it is clearly important that the same encoding is used on both side of the conversion.

Noncompliant Code Example

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.

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

bytesRead = fis.read(data);

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

Compliant Solution

In this compliant solution, the encoding is explicitly specified by using the string encoding as the second parameter of the String constructor.

String encoding = "SomeEncoding" // for example, "UTF-16LE"

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

bytesRead = fis.read(data);

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

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

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

Automated Detection

TODO

Related Vulnerabilities

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

References

[[Encodings 06]]


FIO02-J. Keep track of bytes read and account for character encoding while reading data      08. Input Output (FIO)      FIO30-J. Do not log sensitive information

  • No labels