3

Sha256 hash function gives a longer hashed string in objective c than Java. Extra Zeros being added in objective C, how can I rationalise the hashing?

Objective C:

-(NSString*) sha256:(NSString *)clear{
   const char *s=[clear cStringUsingEncoding:NSASCIIStringEncoding];
   NSData *keyData=[NSData dataWithBytes:s length:strlen(s)];
   uint8_t digest[CC_SHA256_DIGEST_LENGTH]={0};
   CC_SHA256(keyData.bytes, keyData.length, digest);
   NSData *out=[NSData dataWithBytes:digest
   length:CC_SHA256_DIGEST_LENGTH];
   NSString *hash=[out description];
   hash = [hash stringByReplacingOccurrencesOfString:@" " withString:@""];
   hash = [hash stringByReplacingOccurrencesOfString:@"<" withString:@""];
   hash = [hash stringByReplacingOccurrencesOfString:@">" withString:@""];

   return hash;
}

Java

 public static  String generateHashString(String data)
    {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            byte[] dataInBytes = data.getBytes(StandardCharsets.UTF_8);
            md.update(dataInBytes);
            byte[] mdbytes = md.digest();
            StringBuffer hexString = new StringBuffer();
            for (int i=0;i<mdbytes.length;i++) {
                hexString.append(Integer.toHexString(0xFF & mdbytes[i]));
            }

            return hexString.toString();

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

        return null;
    }
Cœur
  • 37,241
  • 25
  • 195
  • 267
RonoKim
  • 184
  • 1
  • 16

1 Answers1

1

Integer.toHexString() on an integer less than 16 will only be one character long, whereas you want the extra '0' character.

You could use String.format():

for (int i = 0; i < mdbytes.length; i++) {
    hexString.append(String.format("%02x", 0xFF & mdbytes[i]));
}

Also, you really should be using StringBuilder rather than StringBuffer in this case because only a single thread is involved.

See Java code To convert byte to Hexadecimal for some alternative solutions to hex-encoding a byte array in Java.

Community
  • 1
  • 1
Daniel Trebbien
  • 38,421
  • 18
  • 121
  • 193
  • Thanks, this worked in getting same hash output, but I need objective-c to work as the java function since changing it will affect android and windows apps consuming the same. – RonoKim Apr 05 '16 at 14:41
  • @RonoKim I don't understand your comment. Can you explain what you mean by "need objective-c to work as the java function"? – Daniel Trebbien Apr 05 '16 at 15:08
  • I was hoping that the change would occur objective-c side, and java function stay put. But I'll make it work thanks – RonoKim Apr 05 '16 at 17:47
  • Lifesaver!! Thank you – Tim Nuwin Jun 24 '16 at 18:52