Skip to content

Instantly share code, notes, and snippets.

@magicianlib
Last active September 14, 2022 05:18
Show Gist options
  • Save magicianlib/8012c52db9c4ea4eec38959a4580675b to your computer and use it in GitHub Desktop.
Save magicianlib/8012c52db9c4ea4eec38959a4580675b to your computer and use it in GitHub Desktop.
Hmac-Sha512
package main
import (
"crypto/hmac"
"crypto/sha512"
"encoding/hex"
"fmt"
)
func main() {
var secret = []byte("The secret key")
var data = []byte("data")
messageMac, err := HmacSHA512(secret, data)
if err != nil {
fmt.Println(err)
}
// Convert byte to hex string
fmt.Println("hmacSha512:", hex.EncodeToString(messageMac))
valid := HmacSHA512Valid(messageMac, secret, data)
fmt.Println("Valid:", valid)
}
func HmacSHA512(secret, data []byte) (mac []byte, err error) {
// hmacMd5: md5.New
hash := hmac.New(sha512.New, secret)
_, err = hash.Write(data)
if err != nil {
return nil, err
}
mac = hash.Sum(nil)
// Convert byte to hex string: hex.EncodeToString(mac)
return
}
func HmacSHA512Valid(expectedMac, secret, data []byte) bool {
messageMac, err := HmacSHA512(secret, data)
if err != nil {
return false
}
return hmac.Equal(messageMac, expectedMac)
}
import org.apache.commons.codec.binary.Hex;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
public class HmacSha512 {
public static void main(String[] args) {
String mac = hmacSha512("data", "The secret key");
System.out.println("hmacSha512: " + mac);
}
public static String hmacSha512(String text, String secret) {
try {
// HmacMD5
Mac mac = Mac.getInstance("HmacSHA512");
mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA512"));
byte[] rawHmac = mac.doFinal(text.getBytes());
// Convert byte to hex string
return Hex.encodeHexString(rawHmac);
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
e.printStackTrace();
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment