I am using the following code to create a sha256 hash of a file, that gets compared against a hash created downstream. The hash created by my code appears to fail very intermittently.
unsigned char hash[CC_SHA256_DIGEST_LENGTH];
if ( CC_SHA256([data bytes], [data length], hash) ) {
NSData *sha256 = [NSData dataWithBytes:hash length:CC_SHA256_DIGEST_LENGTH];
NSString *hash=[sha256 description];
hash = [hash stringByReplacingOccurrencesOfString:@" " withString:@""];
hash = [hash stringByReplacingOccurrencesOfString:@"<" withString:@""];
hash = [hash stringByReplacingOccurrencesOfString:@">" withString:@""];
return hash;
}
return nil;
Hope someone can help me with this? The hash gets generated properly 99.9% of the time, but does fails rarely.
Edit: to clarify, The hash generated on my code is the same as the hash generated by the server most of the time. intermittently, however, the hash generated does not match the one generated downstream. We checked the file with one of the online hashing sites, and the hash generated by the server was correct, while mine did not match the hash generated by the site(defuse.ca)
Add an category to the NSData class with this function and use this instead of description. Also check the case of the hex strings between this string and the one on the server side.
-(NSString *)hexEncodedString
{
unsigned char *bytes = (unsigned char*)[self bytes];
NSInteger length = [self length];
NSMutableString *hexEncodedString = [NSMutableString string];
for (int i = 0; i < length; i++)
{
[hexEncodedString appendFormat:@"%0.2x", bytes[i]];
}
return hexEncodedString;
}