Compare SHA 256 Hashes Example

This program demonstrates comparing SHA 256 hashes of two files to check equality.

Problem Statement

Write a Java program that generates SHA 256 hashes of two files and compares them for equality.

Source Code

1 import java.io.*;
2 import java.security.*;
3
4 public class HashCompareExample {
5 public static void main(String[] args) {
6 System.out.println("Eduinq Hash Compare Example");
7 try {
8 String hash1 = getHash("file1.txt");
9 String hash2 = getHash("file2.txt");
10 System.out.println("Eduinq Hash1: " + hash1);
11 System.out.println("Eduinq Hash2: " + hash2);
12 System.out.println("Eduinq Match: " + hash1.equals(hash2));
13 } catch (Exception e) {
14 System.out.println("Eduinq Exception: " + e.getMessage());
15 }
16 }
17
18 static String getHash(String filename) throws Exception {
19 MessageDigest md = MessageDigest.getInstance("SHA-256");
20 FileInputStream fis = new FileInputStream(filename);
21 byte[] buffer = new byte[1024];
22 int len;
23 while ((len = fis.read(buffer)) != -1) {
24 md.update(buffer, 0, len);
25 }
26 fis.close();
27 byte[] hash = md.digest();
28 StringBuilder sb = new StringBuilder();
29 for (byte b : hash) sb.append(String.format("%02x", b));
30 return sb.toString();
31 }
32 }

Program Output

					Eduinq Hash Compare Example
Eduinq Hash1: 9c56cc51b374c3b0c3f1...
Eduinq Hash2: 9c56cc51b374c3b0c3f1...
Eduinq Match: true
				

Explanation

The program generates SHA 256 hashes for two files using MessageDigest. - It compares the resulting hexadecimal strings to determine if the files are identical. - Exception handling ensures safe operations and prevents runtime errors. - In enterprise systems, hash comparison is widely used for verifying backups, detecting tampering, and ensuring data integrity across distributed systems. Conclusion: Shows comparing SHA 256 hashes of two files for integrity verification.

Quick Links to Explore