...
This noncompliant code example uses a BufferedReader
to wrap an InputStreamReader
object so that sensitive data can be read from a file:
Code Block | ||
---|---|---|
| ||
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 | ||
---|---|---|
| ||
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.
...