Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

Compute HMAC-SHA512 with secret key in java

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

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

The Java 8 lib only provides MessageDigest and KeyGenerator which both only support up to SH256.

Also, Google doesn't give me any result for an implementation to generate a HMAC.

Does someone know a implementation?

I have this code to generate an ordinary SH256 but I guess this doesn't help me much:

   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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...