如何有效地计算IOS中NSData的哈希值

时间:2015-02-07 10:44:36

标签: ios md5 nsdata

这是解决方案,希望它有所帮助。 如果您知道nsdata的大小不像照片那么小文本文件使用方法1。 如果您知道nsdata的大小与某些大型文本文件的视频相同,请使用方法2。

方法1:如果您知道nsdata的大小较小。

  - (NSString*)MD5:(NSData *) data
    {
        // Create byte array of unsigned chars
        unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];

        // Create 16 byte MD5 hash value, store in buffer
        CC_MD5([data bytes], (CC_LONG)data.length, md5Buffer);

        // Convert unsigned char buffer to NSString of hex values
        NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
        for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x",md5Buffer[i]];

        return output;
    }

方法2:如果文件或资产的大小很大(例如,可能在&gt; 50Mb甚至GB)

- (NSString*)MD5:(NSData *) data
{
    CC_MD5_CTX c;
    CC_MD5_Init(&c);

    BOOL didSucceed = NO;

    // Use default value for the chunk size for reading data.
    const size_t chunkSizeForReadingData = 32768; // 32KB

    long chunkSize=chunkSizeForReadingData;

    CFIndex readBytesCount = 0;
    long totalOffset=0;

    long dataLength=[data length];
    NSLog(@"filesize of data:%lu",dataLength);

    long dataTobeReadLeft=dataLength;
    while (dataTobeReadLeft) {
        if (dataTobeReadLeft<chunkSize) {
            uint8_t buffer[dataTobeReadLeft];
            [data getBytes:buffer range:NSMakeRange(totalOffset,dataTobeReadLeft)];
            readBytesCount=dataTobeReadLeft;
            CC_MD5_Update(&c, buffer, (CC_LONG)dataTobeReadLeft);
            dataTobeReadLeft=0;
            didSucceed=YES;
        }else{
            uint8_t buffer[chunkSize];
            [data getBytes:buffer range:NSMakeRange(totalOffset,chunkSize)];
            totalOffset = totalOffset + chunkSize;
            dataTobeReadLeft=dataLength-totalOffset;
            CC_MD5_Update(&c, buffer, (CC_LONG)chunkSize);

        }

    }

    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    if (didSucceed) {
        unsigned char digest[CC_MD5_DIGEST_LENGTH];
        CC_MD5_Final(digest, &c);
        // Convert unsigned char buffer to NSString of hex values
        for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
            [output appendFormat:@"%02x",digest[i]];

    }

    return output;
}

0 个答案:

没有答案