Skip to content

Instantly share code, notes, and snippets.

@matthiaswenz
Created December 20, 2011 11:46
Show Gist options
  • Save matthiaswenz/1501314 to your computer and use it in GitHub Desktop.
Save matthiaswenz/1501314 to your computer and use it in GitHub Desktop.
SHA1FromFile
#import <CommonCrypto/CommonDigest.h>
@implementation SHA1FromFile
+ (NSString *)sha1FromFileAtPath:(NSString *)path {
CFReadStreamRef readStream = CFReadStreamCreateWithFile(kCFAllocatorDefault, CFURLCreateWithFileSystemPath(kCFAllocatorDefault,
(CFStringRef)path,
kCFURLPOSIXPathStyle,
(Boolean)false));
CC_SHA1_CTX ctx;
CC_SHA1_Init(&ctx);
if (!CFReadStreamOpen(readStream)) {
NSLog(@"ERROR!");
}
CFIndex numBytesRead;
do {
uint8_t buffer[1024];
numBytesRead = CFReadStreamRead(readStream, (UInt8 *)buffer, (CFIndex)sizeof(buffer));
if (numBytesRead == -1) {
break;
}
if (numBytesRead == 0) {
continue;
}
CC_SHA1_Update(&ctx, buffer, numBytesRead);
} while (numBytesRead > 0);
uint8_t digest[CC_SHA1_DIGEST_LENGTH];
CC_SHA1_Final(digest, &ctx);
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;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment