Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

In environments that support the fileKey attribute, a more reliable approach is to check that the fileKey attributes of the two files are the same. The fileKey attribute is an object which "uniquely identifies the file" [API 2011], as shown in this compliant solution:

Code Block
bgColor#ccccff
//Identify a file by its path
String filename = // initialized

Path file1 = Paths.get(filename);
BasicFileAttributes attr1 = Files.readAttributes(file1, BasicFileAttributes.class);
Object key1 = attr1.fileKey();

// Open the file for writing
BufferedWriter bw = new BufferedWriter(
  new OutputStreamWriter(Files.newOutputStream(file1)));

// Write to file...
// Close the file
bw.close();

/*
 * A race condition here allows for an attacker to switch
 * out the file for another
 */

// Reopen the file for reading
Path file2 = Paths.get(filename);

BasicFileAttributes attr1 = Files.readAttributes(file1, BasicFileAttributes.class);

BasicFileAttributes attr2 = Files.readAttributes(file2, BasicFileAttributes.class);

Object key1 = attr1.fileKey();

Object key2 = attr2.fileKey();

if ( !key1.equals(key2) ) {
  System.out.println("File tampered with");
  // Handle error
}

BufferedReader br = new BufferedReader(
  new InputStreamReader(Files.newInputStream(file2)));

String line;

while ((line = br.readLine()) != null) {
    System.out.println(line);
}

// Close the file
br.close();

...