...
Code Block | ||
---|---|---|
| ||
//Identify a file by its path String filename = // initialized Path file1 = Paths.get(filename); BasicFileAttributes attr1 = Files.readAttributes(file1, BasicFileAttributes.class); FileTime creation1 = attr1.creationTime(); FileTime modified1 = attr1.lastModifiedTime(); // 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); FileTime creation1 = attr1.creationTime(); FileTime modified1 = attr1.lastModifiedTime(); FileTime creation2 = attr2.creationTime(); FileTime modified2 = attr2.lastModifiedTime(); if ( (!creation1.equals(creation2)) || (!modified1.equals(modified2)) ) { 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(); |
...