Is there any function for creating Hmac256 string in android?

14,114

Solution 1

Calculate the message digest with the hashing algorithm HMAC-SHA256 in the Android platform:

private void generateHashWithHmac256(String message, String key) {
    try {
        final String hashingAlgorithm = "HmacSHA256"; //or "HmacSHA1", "HmacSHA512"

        byte[] bytes = hmac(hashingAlgorithm, key.getBytes(), message.getBytes());

        final String messageDigest = bytesToHex(bytes);

        Log.i(TAG, "message digest: " + messageDigest);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

public static byte[] hmac(String algorithm, byte[] key, byte[] message) throws NoSuchAlgorithmException, InvalidKeyException {
    Mac mac = Mac.getInstance(algorithm);
    mac.init(new SecretKeySpec(key, algorithm));
    return mac.doFinal(message);
}

public static String bytesToHex(byte[] bytes) {
    final char[] hexArray = "0123456789abcdef".toCharArray();
    char[] hexChars = new char[bytes.length * 2];
    for (int j = 0, v; j < bytes.length; j++) {
        v = bytes[j] & 0xFF;
        hexChars[j * 2] = hexArray[v >>> 4];
        hexChars[j * 2 + 1] = hexArray[v & 0x0F];
    }
    return new String(hexChars);
}

This approach does not require any external dependency.

Solution 2

Try below code

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")));
}

Hex.encodeHexString() to use this method, add below dependency to your app gradle.

compile 'org.apache.directory.studio:org.apache.commons.codec:1.8'

This will convert resulted string to hex string same as your php hash_hmac() funtion generates.

Share:
14,114

Related videos on Youtube

Bikesh M
Author by

Bikesh M

I am a &lt;?PHP developer I am a pythonDeveloper : I am a JavaDeveloper { I am an AndroidDeveloper { I am a NodeJsDeveloper {

Updated on September 16, 2022

Comments

  • Bikesh M
    Bikesh M almost 2 years

    Is there any function for creating Hmac256 string in android ? I am using php as my back end for my android application, in php we can create hmac256 string using the php function hash_hmac () [ ref ] is there any function like this in Android

    Please help me.

    • Michael
      Michael over 8 years
      Have you tried using the Mac class with "Hmac256" as the algorithm name?
    • Michael
      Michael over 8 years
      I'm sure you can find plenty of examples of how to use that class if you search around.
  • f.trajkovski
    f.trajkovski over 5 years
    I am getting this using your method: error: cannot find symbol return Hex.encodeHexString(sha256_HMAC.doFinal(data.getBytes("UTF-8‌​")));
  • Jesse Buss
    Jesse Buss about 5 years
    Make sure you're importing the correct Hex object. Should be org.apache.commons.codec.binary.Hex (as specified in the dependency above) not com.google.android.gms.common.util.Hex
  • Kannan_SJD
    Kannan_SJD almost 5 years
    What does this mean final char[] hexArray = "0123456789abcdef".toCharArray();
  • Ryan Amaral
    Ryan Amaral about 3 years
    Is an array of char that is initialised with the hexadecimal numeral system. The word 'hexadecimal' means sixteen because this type of digital numbering system uses 16 different digits from 0-to-9, and A-to-F.