HMAC-SHA256 Algorithm for signature calculation

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

    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();
    }
    
    0 讨论(0)
  • 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)

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 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);
        }
    }
    
    0 讨论(0)
  • 2020-12-12 20:16

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

     Hashing.hmacSha256()
    

    Further documentation here: https://guava.dev/releases/23.0/api/docs/com/google/common/hash/Hashing.html#hmacSha256-byte:A-

    0 讨论(0)
提交回复
热议问题