Monitor File Integrity Example
This program demonstrates monitoring file integrity continuously.
Problem Statement
Write a Java program that monitors file integrity by checking hash periodically.
Source Code
| 1 | import java.io.*; |
| 2 | import java.security.*; |
| 3 | public class FileMonitorExample { |
| 4 | public static void main(String[] args) { |
| 5 | System.out.println("Eduinq File Monitor Example"); |
| 6 | try { |
| 7 | String original=getHash("sample.txt"); |
| 8 | while(true){ |
| 9 | Thread.sleep(5000); |
| 10 | String current=getHash("sample.txt"); |
| 11 | if(!original.equals(current)){ |
| 12 | System.out.println("Eduinq Alert: File Tampered!"); |
| 13 | break; |
| 14 | } else { |
| 15 | System.out.println("Eduinq Integrity OK"); |
| 16 | } |
| 17 | } |
| 18 | } catch(Exception e) { |
| 19 | System.out.println("Eduinq Exception: "+e.getMessage()); |
| 20 | } |
| 21 | } |
| 22 | static String getHash(String file) throws Exception { |
| 23 | MessageDigest md=MessageDigest.getInstance("SHA-256"); |
| 24 | FileInputStream fis=new FileInputStream(file); |
| 25 | byte[] buffer=new byte[1024]; |
| 26 | int len; |
| 27 | while((len=fis.read(buffer))!=-1){ md.update(buffer,0,len); } |
| 28 | fis.close(); |
| 29 | byte[] hash=md.digest(); |
| 30 | StringBuilder sb=new StringBuilder(); |
| 31 | for(byte b:hash) sb.append(String.format("%02x",b)); |
| 32 | return sb.toString(); |
| 33 | } |
| 34 | } |
Program Output
Eduinq File Monitor Example Eduinq Integrity OK Eduinq Alert: File Tampered!
Explanation
Monitors file hash periodically. - Alerts if tampering detected. - Exception handling ensures safe operations. - In enterprise systems, monitoring ensures continuous security. Conclusion: Shows monitoring file integrity.