Harish Harish - 4 months ago 35
Android Question

SHA256 Hash algorithm produces different results in iOS using Common Crypto and OpenSSL

Are the Hash functions different in Apple's Common Crypto and OpenSSL? I'm trying to generate SHA256 of the same string using the below two methods and both produce different results. Am I doing anything different? I am under the impression that the SHA256 algorithm is common across platforms and produce the same result in iOS, Android, Windows etc.

NOTE: When I tried the same thing in Android using MessageDigest.getInstance("SHA-256") I got the same result as CommonCrypto Hash result but the OpenSSL result is different.

// Apple Common Crypto - SHA256
- (NSData *)sha256:(NSData *)data {
unsigned char hashResult[CC_SHA256_DIGEST_LENGTH];
if ( CC_SHA256([data bytes], (unsigned int)[data length], hashResult) ) {
NSData *sha256 = [NSData dataWithBytes:hashResult length:CC_SHA256_DIGEST_LENGTH];
return sha256;
}
}

// SRP OpenSSL - SHA256
- (NSData *)sha256_2:(NSData *)data {
unsigned char hashResult[SHA256_DIGEST_LENGTH];
unsigned char *bin = (unsigned char *) [data bytes];
NSInteger length = sizeof(bin);
[_srpAuth hashWrapper:SRP_SHA256 input:bin size:length output:hashResult];
NSData *sha256 = [NSData dataWithBytes:hashResult length:SHA256_DIGEST_LENGTH];
return sha256;
}

Answer
NSInteger length = sizeof(bin);

Will give you the size of an unsigned char pointer - 4 bytes on a 32 bit device and 8 on a 64 bit.

What you want is

NSInteger length = data.length

since that will give you the number of bytes to be hashed