Log File Hashes Example
This program demonstrates logging file hashes for auditing.
Problem Statement
Write a Java program that logs SHA 256 hashes of files into a log file.
Source Code
| 1 | import java.io.*; |
| 2 | import java.security.*; |
| 3 | public class HashLoggingExample { |
| 4 | public static void main(String[] args) { |
| 5 | System.out.println("Eduinq Hash Logging Example"); |
| 6 | try(PrintWriter pw=new PrintWriter(new FileWriter("hashlog.txt",true))) { |
| 7 | String hash=getHash("sample.txt"); |
| 8 | pw.println("Eduinq File: sample.txt Hash: "+hash); |
| 9 | System.out.println("Eduinq Hash Logged Successfully"); |
| 10 | } catch(Exception e) { |
| 11 | System.out.println("Eduinq Exception: "+e.getMessage()); |
| 12 | } |
| 13 | } |
| 14 | static String getHash(String file) throws Exception { |
| 15 | MessageDigest md=MessageDigest.getInstance("SHA-256"); |
| 16 | FileInputStream fis=new FileInputStream(file); |
| 17 | byte[] buffer=new byte[1024]; |
| 18 | int len; |
| 19 | while((len=fis.read(buffer))!=-1){ md.update(buffer,0,len); } |
| 20 | fis.close(); |
| 21 | byte[] hash=md.digest(); |
| 22 | StringBuilder sb=new StringBuilder(); |
| 23 | for(byte b:hash) sb.append(String.format("%02x",b)); |
| 24 | return sb.toString(); |
| 25 | } |
| 26 | } |
Program Output
Eduinq Hash Logging Example Eduinq Hash Logged Successfully
Explanation
Logs file hashes into text file. - Provides audit trail for integrity checks. - Exception handling ensures safe operations. - In enterprise systems, hash logging supports compliance. Conclusion: Shows logging file hashes.