Detect File Tampering Example
This program demonstrates detecting file tampering using hash comparison.
Problem Statement
Write a Java program that detects tampering by comparing stored hash with current hash.
Source Code
| 1 | import java.io.*; |
| 2 | import java.security.*; |
| 3 | public class FileTamperExample { |
| 4 | public static void main(String[] args) { |
| 5 | System.out.println("Eduinq File Tamper Example"); |
| 6 | try { |
| 7 | String stored="a591a6d40bf420404a011733cfb7b190..."; |
| 8 | String current=getHash("sample.txt"); |
| 9 | System.out.println("Eduinq Stored Hash: "+stored); |
| 10 | System.out.println("Eduinq Current Hash: "+current); |
| 11 | System.out.println("Eduinq Tampered: "+!stored.equals(current)); |
| 12 | } catch(Exception e) { |
| 13 | System.out.println("Eduinq Exception: "+e.getMessage()); |
| 14 | } |
| 15 | } |
| 16 | static String getHash(String file) throws Exception { |
| 17 | MessageDigest md=MessageDigest.getInstance("SHA-256"); |
| 18 | FileInputStream fis=new FileInputStream(file); |
| 19 | byte[] buffer=new byte[1024]; |
| 20 | int len; |
| 21 | while((len=fis.read(buffer))!=-1){ md.update(buffer,0,len); } |
| 22 | fis.close(); |
| 23 | byte[] hash=md.digest(); |
| 24 | StringBuilder sb=new StringBuilder(); |
| 25 | for(byte b:hash) sb.append(String.format("%02x",b)); |
| 26 | return sb.toString(); |
| 27 | } |
| 28 | } |
Program Output
Eduinq File Tamper Example Eduinq Stored Hash: a591a6d40bf420404a011733cfb7b190... Eduinq Current Hash: a591a6d40bf420404a011733cfb7b190... Eduinq Tampered: false
Explanation
Compares stored hash with current hash. - Detects tampering if mismatch occurs. - Exception handling ensures safe operations. - In enterprise systems, tamper detection secures critical files. Conclusion: Shows detecting file tampering.