Objective C HMAC-MD5

- (NSString*) HMACWithSecret:(NSString*) secret andString:(NSString *)str
{
    unsigned long encode = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    
    CCHmacContext    ctx;
    const char       *key = [secret cStringUsingEncoding:encode];
    const char       *string = [str cStringUsingEncoding:encode];
    unsigned char    mac[CC_MD5_DIGEST_LENGTH];
    char             hexmac[2 * CC_MD5_DIGEST_LENGTH + 1];
    char             *p;
    
    CCHmacInit( &ctx, kCCHmacAlgMD5, key, strlen( key ));
    CCHmacUpdate( &ctx, string, strlen(string) );
    CCHmacFinal( &ctx, mac );
    
    p = hexmac;
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++ ) {
        snprintf( p, 3, "%02x", mac[ i ] );
        p += 2;
    }
    
    return [NSString stringWithUTF8String:hexmac];
}

 encode 根据需要可以使用GBK的中文编码,不需要中文的话可以使用UTF-8编码

posted @ 2016-06-01 13:52  小屁孩~  阅读(519)  评论(0编辑  收藏  举报