Skip to content

Instantly share code, notes, and snippets.

@Mehuge
Created May 11, 2022 11:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mehuge/0336c7d925faab16e8e0ac39f159630e to your computer and use it in GitHub Desktop.
Save Mehuge/0336c7d925faab16e8e0ac39f159630e to your computer and use it in GitHub Desktop.
MD5 HASH [Objective C]
#include <CommonCrypto/CommonDigest.h>
- (void) md5:(NSString *)path
{
unsigned char md[CC_MD5_DIGEST_LENGTH];
char hash[CC_MD5_DIGEST_LENGTH*2+1];
CC_MD5_CTX ctx;
char buf[4096];
size_t s;
size_t total = 0;
FILE *fd = fopen([path UTF8String], "r");
if (fd) {
CC_MD5_Init(&ctx);
while ((s = fread(buf, sizeof(*buf), sizeof(buf), fd)) > 0) {
total += s;
CC_MD5_Update(&ctx, buf, (CC_LONG)s);
}
fclose(fd);
CC_MD5_Final(md, &ctx);
for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
sprintf(hash+(i*2), "%02x", md[i]);
}
NSLog(@"HASH %s %lu %@\n", hash, total, path);
}
}
- (void) md5:(NSData *)data offset:(long)offset {
unsigned char md[CC_MD5_DIGEST_LENGTH];
char hash[CC_MD5_DIGEST_LENGTH*2+1];
CC_MD5_CTX ctx;
CC_MD5_Init(&ctx);
CC_MD5_Update(&ctx, [data bytes], (CC_LONG)[data length]);
CC_MD5_Final(md, &ctx);
for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
sprintf(hash+(i*2), "%02x", md[i]);
}
NSLog(@"HASH %lu:%lu (%lu) %s\n", offset, offset + [data length] - 1, [data length], hash);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment