RonoKim
RonoKim

Reputation: 184

Sha256 hash in Objective C and Java

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;
    }

Upvotes: 3

Views: 1235

Answers (1)

Daniel Trebbien
Daniel Trebbien

Reputation: 39218

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.

Upvotes: 1

Related Questions