Java 中的安全数据和 BufferedReader

Secure Data & BufferedReader in Java

我正试图在 Java 中学习更多关于安全编码的知识,并负责使我的代码更合规。如果在我下面创建的示例程序中处理敏感文件数据,我如何确保数据在执行后不会在内存中逗留?

我主要想知道是否有必要用程序原样清除内存。

我已经阅读了多篇文章,但到目前为止我还没有找到直接的解释。如果您希望采用不同的方法以更安全的方式从文件中读取一行,请随时告诉我。阅读了这么多资料后,我开始感到有点迷茫。对新手的任何帮助将不胜感激!

import java.io.*;

public class Data {

private static final String file = "fileData.txt";

public static void main(String[] args) throws IOException {

   BufferedReader br = new BufferedReader(new FileReader(file));

   String data = null;

   try {
      // Read from the file
      data = br.readLine(); 

      // closing BufferedReader
      br.close();


      // Printing a line from file
      System.out.println(data);          
    }
    //define catch to handle the IOException
    catch (IOException e) {
       e.printStackTrace(); // Print Stack Trace for further analysis
    }
}

}

恐怕你是在为一个失败的事业而战。

即使你zeroize the buffer used by BufferedReader (which you would have to access via reflection since it's private) there's no guarantee the JVM hasn't made a copy of it while compacting memory.

引用Thomas Pornin's answer to a related question:

If your security model and context call for zeroing keys, then you should not use Java at all (or just about anything but C and assembly).