HMAC-SHA256 Algorithm for signature calculation

后端 未结 9 715
北海茫月
北海茫月 2020-12-12 19:27

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(         


        
9条回答
  •  天命终不由人
    2020-12-12 20:03

    Here is my solution:

    public static String encode(String key, String data) throws Exception {
      Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
      SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
      sha256_HMAC.init(secret_key);
    
      return Hex.encodeHexString(sha256_HMAC.doFinal(data.getBytes("UTF-8")));
    }
    
    public static void main(String [] args) throws Exception {
      System.out.println(encode("key", "The quick brown fox jumps over the lazy dog"));
    }
    

    Or you can return the hash encoded in Base64:

    Base64.encodeBase64String(sha256_HMAC.doFinal(data.getBytes("UTF-8")));
    

    The output in hex is as expected:

    f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8
    

提交回复
热议问题