用Java中的密钥计算HMAC-SHA512

我想专门构建一个函数,该函数生成带有此站点提供的密钥的HMAC:

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

generator.html

Java 8库仅提供MessageDigest和KeyGenerator,它们均仅最多支持SH256。

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

有人知道实现吗?

我有这段代码来生成普通的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;

}

回答:

希望这可以帮助:

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");

}

}

}

从字节数组转换为十六进制请参阅本计算器答案:这里

以上是 用Java中的密钥计算HMAC-SHA512 的全部内容, 来源链接: utcz.com/qa/429832.html

回到顶部