Compute a checksum on the iPhone from NSData

无人久伴 提交于 2019-11-28 18:23:40

In the <CommonCrypto/CommonDigest.h> header file there should be a CC_MD5 function that will compute an MD5 hash of arbitrary data. It's a C function, so it won't work directly on an NSData, but it should do what you need.

Some more info here (including a wrapper using NSString - should be easy enough to convert to use NSData)

Because everything is better with categories...

Header:

@interface NSData (MD5)
- (NSString *)md5String;
@end

Implementation:

#import <CommonCrypto/CommonDigest.h>


- (NSString *)md5String
{
    void *cData = malloc([self length]);
    unsigned char resultCString[16];
    [self getBytes:cData length:[self length]];

    CC_MD5(cData, (unsigned int)[self length], resultCString);
    free(cData);

    NSString *result = [NSString stringWithFormat:
                        @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
                        resultCString[0], resultCString[1], resultCString[2], resultCString[3],
                        resultCString[4], resultCString[5], resultCString[6], resultCString[7],
                        resultCString[8], resultCString[9], resultCString[10], resultCString[11],
                        resultCString[12], resultCString[13], resultCString[14], resultCString[15]
                        ];
    return result;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!