How do I create an MD5 Hash of a string in Cocoa?

前端 未结 9 1340
半阙折子戏
半阙折子戏 2020-11-28 04:25

I know SHA-1 is preferred, but this project requires I use MD5.

#include 

- (NSString*) MD5Hasher: (NSString*) query {
    NSData* hash         


        
9条回答
  •  心在旅途
    2020-11-28 05:14

    The MD5 function does not return a C string, it returns a pointer to some bytes. You can't treat it as a string.

    If you want to create a string, you need to build a string using the hex values of those bytes. Here is one way to do it as a category on NSData:

    #import 
    @implementation NSData (MMAdditions)
    - (NSString*)md5String
    {
        unsigned char md5[CC_MD5_DIGEST_LENGTH];
        CC_MD5([self bytes], [self length], md5);
        return [NSString stringWithFormat: @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                md5[0], md5[1],
                md5[2], md5[3],
                md5[4], md5[5],
                md5[6], md5[7],
                md5[8], md5[9],
                md5[10], md5[11],
                md5[12], md5[13],
                md5[14], md5[15]
                ];
    }
    @end
    

提交回复
热议问题