Verify File Integrity Example
This program demonstrates verifying file integrity using SHA 256 hash comparison.
Problem Statement
Write a Java program that compares two files by generating SHA 256 hashes.
Source Code
| 1 | import java.io.*; |
| 2 | import java.security.*; |
| 3 | public class FileIntegrityExample { |
| 4 | public static void main(String[] args) { |
| 5 | System.out.println("Eduinq File Integrity Example"); |
| 6 | try { |
| 7 | String h1=getHash("sample.txt"); |
| 8 | String h2=getHash("copy.txt"); |
| 9 | System.out.println("Eduinq Hash1: "+h1); |
| 10 | System.out.println("Eduinq Hash2: "+h2); |
| 11 | System.out.println("Eduinq Match: "+h1.equals(h2)); |
| 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 Integrity Example Eduinq Hash1: a591a6d40bf420404a011733cfb7b190... Eduinq Hash2: a591a6d40bf420404a011733cfb7b190... Eduinq Match: true
Explanation
Generates SHA 256 hashes for both files. - Compares equality to verify integrity. - Exception handling ensures safe operations. - In enterprise systems, integrity checks validate backups and transfers. Conclusion: Shows verifying file integrity with hashes.