How to Find Hash of the Data using HmacSHA1 Algorithm ?
Share
Condition for Finding Hash of the Data using HmacSHA1 Algorithm
Description: To find the hash of data using the HMAC-SHA1 algorithm in Java, the Mac class from the crypto package is used. The process begins by creating an instance of Mac with the HmacSHA1 algorithm using Mac.getInstance("HmacSHA1"). A secret key is then prepared, typically as a SecretKeySpec object, which is initialized with a byte array containing the secret key. After initializing the Mac instance with the key using the mac.init(secretKey) method, the data to be hashed is passed to the instance using mac.update(data.getBytes()). Finally, the hash is generated by calling mac.doFinal(), which returns the result as a byte array. This byte array can then be converted to a hexadecimal or Base64 string for display or storage. The resulting hash serves as a secure digest of the data, ensuring integrity and authentication when using HMAC-SHA1.
Sample Code
package JavaSamples2;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class HmacSHA1Hashing {
public static void main(String args[]){
try {
String data = "This is the data to hash.";
String secretKey = "MySecretKey";
Mac mac = Mac.getInstance("HmacSHA1");
SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1");
mac.init(keySpec);
byte[] hmacBytes = mac.doFinal(data.getBytes());
String hmacHash = Base64.getEncoder().encodeToString(hmacBytes);
System.out.println("HMAC-SHA1 Hash: " + hmacHash);
} catch (NoSuchAlgorithmException | InvalidKeyException | IllegalStateException e) {
System.out.println(e.getMessage());
}
}
}