HMAC-SHA256 Algorithm for signature calculation

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

    This is working fine for me

    I have add dependency

    compile 'commons-codec:commons-codec:1.9'
    

    ref: http://mvnrepository.com/artifact/commons-codec/commons-codec/1.9

    my function

    public String encode(String key, String data) {
        try {
    
            Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
            SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
            sha256_HMAC.init(secret_key);
    
            return new String(Hex.encodeHex(sha256_HMAC.doFinal(data.getBytes("UTF-8"))));
    
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    
        return null;
    }
    

提交回复
热议问题