0

I want to hash a file (using SHA1 at the moment). Here is the function:

static inline __attribute__((always_inline)) NSString *SHA1String(NSData *data) {
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    CC_SHA1(data.bytes, (CC_LONG)data.length, digest);
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    for (int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++) {
        [output appendFormat:@"%02x", digest[i]];
    }
    return output;
}

And here are the two different methods of loading the data:

CFURLRef filePath = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, CFSTR("/path/to/file"), kCFURLPOSIXPathStyle, false);
CFDataRef cfFileData = CFURLCreateData(kCFAllocatorDefault, filePath, kCFStringEncodingUTF8, false);
NSString *cfFileHash = SHA1String((__bridge NSData *)cfFileData);

NSData *fileData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:@"/path/to/file"]];
NSString *fileHash = SHA1String((__bridge NSData *)fileData);

NSLog(@"Hashes: %@ - %@", cfFileHash, fileHash);

The hashes differ and I wonder what is causing this. I'd like to use the CoreFoundation API, but if the file hash differs, that'd be bad. I use another file manager to view the sha1 of the file and it matches the one from NSData.

Any insights appreciated.

Janosch Hübner
  • 1,584
  • 25
  • 44
  • You aren't checking for errors here. It is possible that `CFURLCreateData` is failing, in which case you're likely generating an empty hash (da39a3ee5e6b4b0d3255bfef95601890afd80709) – Rob Napier Feb 03 '20 at 15:53
  • It is not the empty hash. It is 1edcf9af5f3105b396241fec15916adc592db185 for CF and 3d2b417eaa52c74d2ed9834adecf52b033d15b71 for NS. And the latter is the correct and expected – Janosch Hübner Feb 03 '20 at 15:55
  • I still recommend checking for errors. I then recommend checking that the actual string is the same. The fact that you're getting different results indicates that something you believe is true is not true. The goal is to figure out what line of code generates a different result than you believe it does. For example, what is the result of `[fileData isEqual:(_bridge NSData*)cfFileData]`? – Rob Napier Feb 03 '20 at 16:04

0 Answers0