Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 4.0

...

Compliant Solution (ByteBuffer)

Wiki MarkupThis compliant solution uses methods provided by class {{ByteBuffer}} (see \ [[API 2006|AA. References#API 06] \] [{{ByteBuffer}}|http://download.oracle.com/javase/6/docs/api/java/nio/ByteBuffer.html]) to correctly extract an {{int}} from the original input value. It wraps the input byte array with a {{ByteBuffer}}, sets the byte order to little-endian, and extracts the {{int}}. The result is stored in the integer {{serialNumber}}. Class {{ByteBuffer}} provides analogous get and put methods for other numeric types.

Code Block
bgColor#ccccff
	 
try {
  DataInputStream dis = null;
  try {
    dis = new DataInputStream( new FileInputStream("data"));
    byte[] buffer = new byte[4];
    int bytesRead = dis.read(buffer);  // Bytes are read into buffer
    if (bytesRead != 4) {
      throw new IOException("Unexpected End of Stream");
    }
    int serialNumber = 
        ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN).getInt();
  } finally {
    if (dis != null) {
  try {
    dis.close();
  } catch (IOException x) {
    // handle error
  }
    }
  }
} catch (IOException x) {
  // handle error
}

...

MITRE CWE

CWE-198. Use of incorrect byte ordering

Bibliography

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="6b4ebc12-c88c-40b6-bac1-a140b1de312b"><ac:plain-text-body><![CDATA [ [[API 2006AA. References#API 06] ]

[Class ByteBufferhttp: //download.oracle.com/javase/6/docs/api/java/nio/ByteBuffer.html]: Methods wrap and order. [Class Integerhttp://download.oracle.com/javase/6/docs/api/java/lang/Integer.html]: method reverseBytes

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="8a108eb1-282d-4a7d-8d2f-3b7ca8eaef15"><ac:plain-text-body><! [CDATA[ [[Cohen 1981AA. References#Cohen 81]]

On Holy Wars and a Plea for Peace

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="73b0cb07-5f92-4c58-847e-370cfb3641b6"><ac:plain-text-body><![CDATA[

[ [Harold 1997AA. References#Harold 97] ]

Chapter 2, Primitive Data Types, Cross-Platform Issues ]]></ac:plain-text-body></ac:structured-macro>

...

FIO11-J. Do not attempt to read raw binary data as character data      12. Input Output (FIO)