-1

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;
}
AndroidDev
  • 5,193
  • 5
  • 37
  • 68
  • what value are you getting for `length` in the openSSL case? – Paulw11 Aug 09 '16 at 10:22
  • Same as the other Hash results (32 bytes). iOS CC/Android/MacOS OpenSSL Cmd line Hash result: <2910ff11 5706d967 044d624a 3a63c0ae 7ae5c5bf b5442372 e47f717d 94b5c18c>. Whereas OpenSSL Hash result: <6a382a3e f2034daf 1fbbc457 23dfeb24 123b112b ca2a14c0 27c5b9d9 8db6e996> – AndroidDev Aug 09 '16 at 10:39
  • Are you sure? `sizeof(bin)` should give 4 on a 32 bit device and 8 on a 64 bit device. You probably want `length = data.length;` – Paulw11 Aug 09 '16 at 10:45
  • Paul, pardon my stupidity, that was it :) Now its producing the same result – AndroidDev Aug 09 '16 at 10:51

1 Answers1

2
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

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

Paulw11
  • 108,386
  • 14
  • 159
  • 186