Updated 26 October 2021
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.
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:
The Function that will give us our desired Hash in a String.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
private String MyHashHmac(String secret, String data){ String returnString = ""; try { SecretKeySpec keySpec = new SecretKeySpec(secret.getBytes(),"HmacSHA1"); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(keySpec); byte[] dataByteArray = mac.doFinal(data.getBytes()); BigInteger hash = new BigInteger(1,dataByteArray); returnString = hash.toString(); }catch (Exception e){ e.printStackTrace(); } return returnString; } |
Calling this Function:
1 2 3 4 5 |
String MySecret = "MySecret"; //Replace with your own Secret String MyData = "MyData"; // Replace with your data String Hash_hmac_result = MyHashHmac(MySecret,MyData); Log.d("TAG", "result : " +Hash_hmac_result); |
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.