HMAC using SHA512


Michael Agbenyegah July 25, 2023

HMACSHA512 Encryption

Perform HMAC (Hash-based Message Authentication Code) encryption using SHA-512 in different programming languages.

Remember that HMAC is commonly used for verifying the integrity and authenticity of a message by combining a secret key with the message and hashing the result. Both the sender and receiver must use the same secret key to generate and verify the HMAC. Keep your secret key secure and ensure that you handle the key properly in your application to maintain the security of the HMAC.

var message = "9221USD20Narration of the txn2023-07-2510029944485";
var secret = "K7pnqQRCmOEDdOMpN+ujCQ==";

A web service requires me to encrypt combined payload values using HMAC and convert the result to hexadecimal (HEX). Let's look at how this will be done in different languages.


var requestSignature = ComputeSignature(secret, message);
public string ComputeSignature(string secret, string message)
    using (var hmacsha256 = new HMACSHA512(Encoding.UTF8.GetBytes(secret)))
        var bytes = Encoding.UTF8.GetBytes(message);
        var hashedBytes = hmacsha256.ComputeHash(bytes);

        return BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();



String requestSignature = "";
try {
    requestSignature = hmacWithJava(message,secret);
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
    throw new RuntimeException(e);
public static String hmacWithJava(String data, String secret)
        throws NoSuchAlgorithmException, InvalidKeyException {
    String algorithm = "HmacSHA512";
    SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(), algorithm);
    Mac mac = Mac.getInstance(algorithm);
    return toHexString(mac.doFinal(data.getBytes()));
public static String toHexString(byte[] array) {
    return DatatypeConverter.printHexBinary(array).toLowerCase();