HMAC-SHA256 Algorithm for signature calculation

后端 未结 9 739
北海茫月
北海茫月 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:06

    If but any chance you found a solution how to calculate HMAC-SHA256 here, but you're getting an exception like this one:

    java.lang.NoSuchMethodError: No static method encodeHexString([B)Ljava/lang/String; in class Lorg/apache/commons/codec/binary/Hex; or its super classes (declaration of 'org.apache.commons.codec.binary.Hex' appears in /system/framework/org.apache.http.legacy.boot.jar)

    Then use:

    public static String encode(String key, String data) {
        try {
            Mac hmac = Mac.getInstance("HmacSHA256");
            SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
            hmac.init(secret_key);
            return new String(Hex.encodeHex(hmac.doFinal(data.getBytes("UTF-8"))));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    

提交回复
热议问题