该方法是写在工具类中的,而不是写在NSString的类别中
方法的声明:
/**
* 使用hmac-md5加密
*
* @param clearText 原文
* @param secret 秘钥
*
* @return 密文
*/
+ (NSString *)getHmacmd5:(NSString *)clearText withSecret:(NSString *)secret;
方法的实现:
//密码进行hmac-md5加密
+ (NSString *)getHmacmd5:(NSString *)clearText withSecret:(NSString *)secret{
CCHmacContext ctx;
//使用GBK编码
unsigned long encode = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
const char *key = [secret cStringUsingEncoding:encode];
const char *str = [clearText 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, str, strlen(str));
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 stringWithCString:hexmac encoding:encode];
}