Create hash in Android equivalent to hash_hmac method of php

Updated 26 October 2021

Save

In this Blog, we will learn about how to create a keyed hash value in android which gives the same output as the hash_hmac method in PHP.

Before Starting, we should first look into what exactly the hash_hmac method in PHP does?

The hash_hmac function in PHP returns a  keyed hash value using the HMAC method. You can check the official documentation for the PHP function over here.

Implementing this is easy but there is no exactly in built function for this, so we will have to follow a small procedure.

APPROACH/ PROCEDURE :

  1. Create a new Object of SecretKeySpec class by passing your secret and “HmacSHA1” as the inputs.
  2. Create an instance of Mac by calling function, Mac.getInstance() and passing “HmacSHA1” as an argument.
  3. Initialize the Mac instance obtained above by calling the init function and passing the SecretKeySpec object in the init function.
  4.  Create a new byte array and assign it the value returned by the Mac.doFinal function.
    Please note in the Mac.dofinal function you need to pass the bytes value of your data that you want to convert into hashes.

    With all these steps,  you have successfully converted your data to hashes but this data is in byte form.
    To convert your data into a String that can be used as a single hash string you need to follow below-mentioned steps:

  5.  Create a new object of Big Integer class by passing 1 as the first argument and the byte array obtained above as the second argument.
  6.  Call the toString() method on this instance of the Big integer and the value returned is your hash in a String.

CODE : 

The Function that will give us our desired Hash in a String.

Calling this Function:

author
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Start a Project


    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home