HMAC-SHA256 Algorithm for signature calculation

2019-01-21 10:45发布

I am trying to create a signature using the HMAC-SHA256 algorithm and this is my code. I am using US ASCII encoding.

final Charset asciiCs = Charset.forName("US-ASCII");
final Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
final SecretKeySpec secret_key = new javax.crypto.spec.SecretKeySpec(asciiCs.encode("key").array(), "HmacSHA256");
final byte[] mac_data = sha256_HMAC.doFinal(asciiCs.encode("The quick brown fox jumps over the lazy dog").array());
String result = "";
for (final byte element : mac_data)
{
    result += Integer.toString((element & 0xff) + 0x100, 16).substring(1);
}
System.out.println("Result:[" + result + "]");

The result that I am getting from the above code is:

f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8

This is same as to that of shown in the wiki

HMAC_SHA256("key", "The quick brown fox jumps over the lazy dog") = 0x f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8

except for the 0x.

I am looking for ideas/comments if I am doing everything right or may be I can improve my code.

9条回答
成全新的幸福
2楼-- · 2019-01-21 11:07

The answer that you got there is correct. One minor thing in the code above, you need to init(key) before you can call doFinal()

    final Charset charSet = Charset.forName("US-ASCII");
    final Mac sha256_HMAC = Mac.getInstance("HmacSHA256");

    final SecretKeySpec secret_key = new javax.crypto.spec.SecretKeySpec(charSet.encode("key").array(), "HmacSHA256");
    try {
        sha256_HMAC.init(secret_key);
    } catch (InvalidKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    ...
查看更多
放荡不羁爱自由
3楼-- · 2019-01-21 11:07

If you're using Guava, its latest release now lets you use

 Hashing.hmacSha256()
查看更多
霸刀☆藐视天下
4楼-- · 2019-01-21 11:13

Here is my solution:

public String HMAC_SHA256(String secret, String message)
{
    String hash="";
    try{
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
        sha256_HMAC.init(secret_key);

        hash = Base64.encodeToString(sha256_HMAC.doFinal(message.getBytes()), Base64.DEFAULT);
    }catch (Exception e)
    {

    }
    return hash.trim();
}
查看更多
登录 后发表回答