用java中的密钥计算HMAC-SHA512

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39355241/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 21:04:04  来源:igfitidea点击:

Compute HMAC-SHA512 with secret key in java

javahmac

提问by PowerFlower

i want to build excatly a function which produces a HMAC with a secret key like this site provides:

我想完全构建一个函数,该函数生成一个带有密钥的 HMAC,就像这个站点提供的:

http://www.freeformatter.com/hmac-generator.html

http://www.freeformatter.com/hmac-generator.html

The java 8 lib only provides MessageDigest and KeyGenerator which both only supports up to SH256.

java 8 lib 只提供 MessageDigest 和 KeyGenerator,两者都只支持最高 SH256。

Also google doesnt give me any result to an implementation to generate a HMAC.

此外,谷歌没有给我任何生成 HMAC 的实现结果。

Does someone know a implementation?

有人知道实现吗?

I have this code to generate an ordinary SH256 but i guess this doesnt help me much:

我有这个代码来生成一个普通的 SH256,但我想这对我没有多大帮助:

   public static String get_SHA_512_SecurePassword(String passwordToHash) throws Exception {
    String generatedPassword = null;

    MessageDigest md = MessageDigest.getInstance("SHA-512");
    byte[] bytes = md.digest(passwordToHash.getBytes("UTF-8"));
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < bytes.length; i++) {
        sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
    }
    generatedPassword = sb.toString();
    System.out.println(generatedPassword);
    return generatedPassword;
}

采纳答案by dvsakgec

Hope this helps:

希望这可以帮助:

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class Test1 {

    private static final String HMAC_SHA512 = "HmacSHA512";

    public static void main(String[] args) {
        Mac sha512Hmac;
        String result;
        final String key = "Welcome1";

        try {
            final byte[] byteKey = key.getBytes(StandardCharsets.UTF_8);
            sha512Hmac = Mac.getInstance(HMAC_SHA512);
            SecretKeySpec keySpec = new SecretKeySpec(byteKey, HMAC_SHA512);
            sha512Hmac.init(keySpec);
            byte[] macData = sha512Hmac.doFinal("My message".getBytes(StandardCharsets.UTF_8));

            // Can either base64 encode or put it right into hex
            result = Base64.getEncoder().encodeToString(macData);
            //result = bytesToHex(macData);
        } catch (UnsupportedEncodingException | InvalidKeyException | NoSuchAlgorithmException e) {
            e.printStackTrace();
        } finally {
            // Put any cleanup here
            System.out.println("Done");
        }
    }
}

For converting from byte array to hex refer this stackoverflow answer : here

要将字节数组转换为十六进制,请参阅此 stackoverflow 答案:此处

回答by Dhanendra Pratap Singh

The simplest way can be -

最简单的方法可以是——

private static final String HMAC_SHA512 = "HmacSHA512";

private static String toHexString(byte[] bytes) {
    Formatter formatter = new Formatter();
    for (byte b : bytes) {
        formatter.format("%02x", b);
    }
    return formatter.toString();
}

public static String calculateHMAC(String data, String key)
    throws SignatureException, NoSuchAlgorithmException, InvalidKeyException
{
    SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), HMAC_SHA512);
    Mac mac = Mac.getInstance(HMAC_SHA512);
    mac.init(secretKeySpec);
    return toHexString(mac.doFinal(data.getBytes()));
}

public static void main(String[] args) throws Exception {
    String hmac = calculateHMAC("data", "key");
    System.out.println(hmac);
}

You can change the HMAC_SHA512 variable to any of the Mac algorithm and the code will work the same way.

您可以将 HMAC_SHA512 变量更改为任何 Mac 算法,代码将以相同的方式工作。