Implement HMACSHA256 in Java Easily
In Java, you can implement HmacSHA256 using the Mac class in the javax.crypto package. Here is an example code that encrypts data using the HmacSHA256 algorithm.
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
public class HmacSHA256Example {
public static void main(String[] args) {
String data = "Hello, World!";
String key = "secretKey";
try {
Mac hmacSHA256 = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "HmacSHA256");
hmacSHA256.init(secretKey);
byte[] hash = hmacSHA256.doFinal(data.getBytes());
String encodedHash = Base64.getEncoder().encodeToString(hash);
System.out.println("HMAC-SHA256 hash: " + encodedHash);
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
e.printStackTrace();
}
}
}
In the code above, first an instance of HmacSHA256 is created and initialized with a specific key. Then the data is encrypted and the encrypted result is converted to a string in Base64 encoding and outputted.
Please note that in this example, the encrypted result has been converted using Base64 encoding. If you need the original byte array, you can directly use the hash variable.