user642966
user642966

Reputation: 33

SHA-256 hashing yields the wrong result in Android

I am trying to encrypt 12345 using 1111 as salt using SHA-256 encoding and the answer I get is: 010def5ed854d162aa19309479f3ca44dc7563232ff072d1c87bd85943d0e930 which is not same as the value returned by this site.

Here's the code snippet:

public String getHashValue(String entity, String salt){
    byte[] hashValue = null;
    try {
        MessageDigest digest =  MessageDigest.getInstance("SHA-256");
        digest.update(entity.getBytes("UTF-8"));
        digest.update(salt.getBytes("UTF-8"));
        hashValue = digest.digest();
    } catch (NoSuchAlgorithmException e) {
        Log.i(TAG, "Exception "+e.getMessage());
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return BasicUtil.byteArrayToHexString(hashValue);
}

I have verified my printing method with a sample from SO and result is fine. Can someone tell me what's wrong here?

And just to clarify - when I encrypt same value & salt in iOS code, the returned value is same as the value given by the converting site.

Upvotes: 3

Views: 2413

Answers (1)

Akdeniz
Akdeniz

Reputation: 1270

If you fill optional part for hmac secret in that site, HmacSHA256 algorithm will be used. Same result can be produced with this function:

public static String getHmac(String entity, String salt) throws Exception{
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(new SecretKeySpec(salt.getBytes(), "HmacSHA1"));
    byte[] bs = mac.doFinal(entity.getBytes());
    return new HexDumpEncoder().encode(bs); // use your favorite hex converter
}

If you want to get the same output from that site, try to hash this value "123451111" without hmac secret.

As obvious, calling MessageDigest.update twice is equivalent to calling it once with concatenated value.

Upvotes: 2

Related Questions