Generate HMAC Example
This program demonstrates generating HMAC using SHA 256.
Problem Statement
Write a Java program that generates HMAC for a file using a secret key.
Source Code
| 1 | import java.io.*; |
| 2 | import javax.crypto.*; |
| 3 | import javax.crypto.spec.SecretKeySpec; |
| 4 | public class HMACExample { |
| 5 | public static void main(String[] args) { |
| 6 | System.out.println("Eduinq HMAC Example"); |
| 7 | try(FileInputStream fis=new FileInputStream("sample.txt")) { |
| 8 | byte[] key="eduinqsecret".getBytes(); |
| 9 | SecretKeySpec sk=new SecretKeySpec(key,"HmacSHA256"); |
| 10 | Mac mac=Mac.getInstance("HmacSHA256"); |
| 11 | mac.init(sk); |
| 12 | byte[] buffer=new byte[1024]; |
| 13 | int len; |
| 14 | while((len=fis.read(buffer))!=-1){ mac.update(buffer,0,len); } |
| 15 | byte[] hmac=mac.doFinal(); |
| 16 | StringBuilder sb=new StringBuilder(); |
| 17 | for(byte b:hmac) sb.append(String.format("%02x",b)); |
| 18 | System.out.println("Eduinq HMAC: "+sb.toString()); |
| 19 | } catch(Exception e) { |
| 20 | System.out.println("Eduinq Exception: "+e.getMessage()); |
| 21 | } |
| 22 | } |
| 23 | } |
Program Output
Eduinq HMAC Example Eduinq HMAC: 9c56cc51b374c3b0c3f1...
Explanation
HMAC uses secret key with hash function. - Provides integrity and authenticity. - Exception handling ensures safe operations. - In enterprise systems, HMAC secures API communication. Conclusion: Shows generating HMAC for files.