Compute HMAC-SHA512 with secret key in java

ⅰ亾dé卋堺 提交于 2019-11-27 13:49:49

问题


i want to build excatly 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 supports up to SH256.

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

Does someone know a implementation?

I have this code to generate an ordinary SH256 but i guess this doesnt 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;
}

回答1:


Hope this helps:

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class Test1 {
    public static void main(String[] args) {
        Mac sha512_HMAC = null;
        String result = null;
        String key =  "Welcome1";

        try{
            byte [] byteKey = key.getBytes("UTF-8");
            final String HMAC_SHA512 = "HmacSHA512";
            sha512_HMAC = Mac.getInstance(HMAC_SHA512);      
            SecretKeySpec keySpec = new SecretKeySpec(byteKey, HMAC_SHA512);
            sha512_HMAC.init(keySpec);
            byte [] mac_data = sha512_HMAC.
             doFinal("My message".getBytes("UTF-8"));
            //result = Base64.encode(mac_data);
            result = bytesToHex(mac_data);
            System.out.println(result);
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            System.out.println("Done");
        }
    }

    public static String bytesToHex(byte[] bytes) {
        final  char[] hexArray = "0123456789ABCDEF".toCharArray();
        char[] hexChars = new char[bytes.length * 2];
        for ( int j = 0; j < bytes.length; j++ ) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }
}

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




回答2:


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.



来源:https://stackoverflow.com/questions/39355241/compute-hmac-sha512-with-secret-key-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!