Generate SHA-256 Hash Example
This program demonstrates generating SHA-256 hash of a file.
Problem Statement
Write a Java program that generates SHA-256 hash of a file content.
Source Code
| 1 | import java.io.*; |
| 2 | import java.security.*; |
| 3 | public class SHAHashExample { |
| 4 | public static void main(String[] args) { |
| 5 | System.out.println("Eduinq SHA-256 Hash Example"); |
| 6 | try(FileInputStream fis=new FileInputStream("sample.txt")) { |
| 7 | MessageDigest md=MessageDigest.getInstance("SHA-256"); |
| 8 | byte[] buffer=new byte[1024]; |
| 9 | int len; |
| 10 | while((len=fis.read(buffer))!=-1){ |
| 11 | md.update(buffer,0,len); |
| 12 | } |
| 13 | byte[] hash=md.digest(); |
| 14 | StringBuilder sb=new StringBuilder(); |
| 15 | for(byte b:hash) sb.append(String.format("%02x",b)); |
| 16 | System.out.println("Eduinq SHA-256 Hash: "+sb.toString()); |
| 17 | } catch(Exception e) { |
| 18 | System.out.println("Eduinq Exception: "+e.getMessage()); |
| 19 | } |
| 20 | } |
| 21 | } |
Program Output
Eduinq SHA-256 Hash Example Eduinq SHA-256 Hash: a591a6d40bf420404a011733cfb7b190...
Explanation
SHA-256 generates stronger hash than MD5. - Provides high security for integrity checks. - Exception handling ensures safe operations. - In enterprise systems, SHA-256 is used for secure verification. Conclusion: Shows generating SHA-256 hash.