HMAC-SHA256 Algorithm for signature calculation

后端 未结 9 699
北海茫月
北海茫月 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 19:57

    Try this

    Sorry for being late, I have tried all above answers but none of them is giving me correct value, After doing the lot of R&D I have found a simple way that gives me exact value.

    1. Declare this method in your class

      private String hmacSha(String KEY, String VALUE, String SHA_TYPE) {
      try {
          SecretKeySpec signingKey = new SecretKeySpec(KEY.getBytes("UTF-8"), SHA_TYPE);
          Mac mac = Mac.getInstance(SHA_TYPE);
          mac.init(signingKey);
          byte[] rawHmac = mac.doFinal(VALUE.getBytes("UTF-8"));
          byte[] hexArray = {(byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f'};
          byte[] hexChars = new byte[rawHmac.length * 2];
          for ( int j = 0; j < rawHmac.length; j++ ) {
              int v = rawHmac[j] & 0xFF;
              hexChars[j * 2] = hexArray[v >>> 4];
              hexChars[j * 2 + 1] = hexArray[v & 0x0F];
          }
          return new String(hexChars);
      }
      catch (Exception ex) {
          throw new RuntimeException(ex);
      }
      

      }

    2. Use this like

      Log.e("TAG", "onCreate: "+hmacSha("key","text","HmacSHA256"));
      

    Verification

    1.Android studio output 2. Online HMAC generator Output(Visit here for Online Genrator)

提交回复
热议问题