使用java

时间:2016-09-06 18:05:48

标签: java hmac

我想兴奋地构建一个函数,它生成一个带有密钥的HMAC,就像这个站点提供的那样:

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

java 8 lib只提供MessageDigest和KeyGenerator,它们最多只支持SH256。

google也没有给我任何结果来生成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;
}

4 个答案:

答案 0 :(得分:16)

希望这会有所帮助:

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

要从字节数组转换为十六进制,请参阅此stackoverflow应答:here

答案 1 :(得分:14)

最简单的方法可以是 -

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

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

答案 2 :(得分:1)

此外,您可以在Apache Commons codec之前使用一些包装纸:

while(!push_button2.read())
    sleep(0.01)

答案 3 :(得分:0)

您可以使用 Caesar(版本 0.6.0 或更高版本):

int blockSize = 128;
String secretKey = "My secret key";
String message = "Message to hash";
System.out.println(
    new Hmac(
        new ImmutableMessageDigest(
            MessageDigest.getInstance("SHA-512")
        ),
        blockSize,
        new PlainText(secretKey),
        new PlainText(message)
    ).asHexString()
);