Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: code compiles

...

This noncompliant code example uses a BufferedReader to wrap an InputStreamReader object so that sensitive data can be read from a file:

Code Block
bgColor#FFCCCC
void exampleFuntion() throws IOException{
  BufferedReader br = new BufferedReader(new InputStreamReader(
  new FileInputStream("file")));
  // Read from the file

}

Compliant Solution

This compliant solution uses a directly allocated NIO (new I/O) buffer to read sensitive data from the file. The data can be cleared immediately after use and is not cached or buffered at multiple locations. It exists only in the system memory.

Code Block
bgColor#ccccff
void exampleFuntion() throws IOException{
  ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024);
  try(FileChannel rdr = (new FileInputStream("file")).getChannel()){
   	while (rdr.read(buffer) > 0) {
      // Do something with the buffer
	  buffer.clear();
	}
  } 
  catch (Exception e) {
    // Handle error
  }
} 

Note that manual clearing of the buffer data is mandatory because direct buffers are exempt from garbage collection.

...