#import "AlgorithmManager.h"
#import <CommonCrypto/CommonCrypto.h>
@implementation AlgorithmManager
+ (NSString *)signWithHmacSHA256:(NSString *)input withKey:(NSString *)key{
const char *cKey = [key cStringUsingEncoding:NSASCIIStringEncoding];
const char *cData = [input cStringUsingEncoding:NSASCIIStringEncoding];
unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];
CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
NSData *HMACData = [[NSData alloc] initWithBytes:cHMAC length:sizeof(cHMAC)];
const unsigned char *buffer = (const unsigned char *)[HMACData bytes];
NSString *HMAC = [NSMutableString stringWithCapacity:HMACData.length * 2];
for (int i = 0; i < HMACData.length; ++i)
HMAC = [HMAC stringByAppendingFormat:@"%02lx", (unsigned long)buffer[i]];
return HMAC;
}
@end
HmacSHA256 实现原理与HmacSHA1原理一样,只需要设置两个参数即可。
1. CC_SHA1_DIGEST_LENGTH -> CC_SHA256_DIGEST_LENGTH
2. kCCHmacAlgSHA1 ->kCCHmacAlgSHA256
同理 ,其它类型也可以设置。类型如下:
enum {
kCCHmacAlgSHA1,
kCCHmacAlgMD5,
kCCHmacAlgSHA256,
kCCHmacAlgSHA384,
kCCHmacAlgSHA512,
kCCHmacAlgSHA224
};