#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonHMAC.h>
@implementation HmacUtils
/**
* 加密方式,MAC算法: HmacSHA256
*
* @param plaintext 要加密的文本
* @param key 秘钥
*
* @return 加密后的字符串
*/
+ (NSString *)hmac:(NSString *)plaintext withKey:(NSString *)key
{
const charchar *cKey = [key cStringUsingEncoding:NSASCIIStringEncoding];
const charchar *cData = [plaintext cStringUsingEncoding:NSASCIIStringEncoding];
unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];
CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
NSData *HMACData = [NSData dataWithBytes:cHMAC length:sizeof(cHMAC)];
const unsigned charchar *buffer = (const unsigned charchar *)[HMACData bytes];
NSMutableString *HMAC = [NSMutableString stringWithCapacity:HMACData.length * 2];
for (int i = 0; i < HMACData.length; ++i){
[HMAC appendFormat:@"%02x", buffer[i]];
}
return HMAC;
}
@end
网友评论