0

I'm trying to convert this php function:

string hash_hmac ( string $algo , string $data , string $key [, bool $raw_output = false ] )

where algo = SHA-256, data = dd-mm-yyy, key = "password"

I have write a code with Message Digest that calculate sha-256 on the concatenation data + key, but the output it's different form the output of php function.

Any help for write this php function into android java?

In fact, I set for String key a personal password and for String s a date. Now when I run the app and generete the hmacsha256 that I add to a url get, the value hmacSha256 that I print it's different form a hmacSha256 calculate into iOS.

I used this code adapted from one answer :

String PRIVATE_KEY = (String) "asf";
String dateInString = "2015-04-26";  // Start date
String sdf = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
String Token = (String) sdf + PRIVATE_KEY;

private static String toHexString(final byte[] bytes) {
    final Formatter formatter = new Formatter();
    for (final byte b : bytes) {
        formatter.format("%02x", b);
    }
    return formatter.toString();
}

public static String hmacSha256(final String PRIVATE_KEY, final String sdf) {
    try {
        final Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(PRIVATE_KEY.getBytes(), "HmacSHA256"));
        return toHexString(mac.doFinal(sdf.getBytes()));
    }
    catch (final Exception e) {
        // ...
    }
    return PRIVATE_KEY;
}

But when I print hmacSha256(sdf,PRIVATE_KEY), my output is: 76934121da91e03df3ca531057cdca132ebc7fe37ba60fc12da11dba285e3ba2

and this value it's different respect to hmacSha256 genereted by iOS. What is wrong here.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
dev_
  • 395
  • 1
  • 3
  • 16
  • 1
    http://stackoverflow.com/questions/7166129/how-can-i-calculate-the-sha-256-hash-of-a-string-in-android ? – Stan Apr 27 '15 at 12:34
  • In Stack Overflow, you should edit your question to add relevant information and **never** put it in answers. And you should add the value generated by iOS to help others to understand what can happen. – Serge Ballesta Apr 30 '15 at 06:22

1 Answers1

4

This is how I did a HmacSHA256 implementation:

private static String toHexString(final byte[] bytes) {
    final Formatter formatter = new Formatter();
    for (final byte b : bytes) {
        formatter.format("%02x", b);
    }
    return formatter.toString();
}

public static String hmacSha256(final String key, final String s) {
    try {
        final Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(key.getBytes(), "HmacSHA256");
        return toHexString(mac.doFinal(s.getBytes()));
    }
    catch (final Exception e) {
        // ...
    }
}
shkschneider
  • 17,833
  • 13
  • 59
  • 112