HMAC-SHA1 HMAC-SHA256 两种加密方式

HMAC (Hash-based Message Authentication Code) 常用于接口签名验证

支持的算法有 md5、sha1、sha256、sha512、adler32、crc32、crc32b、fnv132、fnv164、fnv1a32、fnv1a64、gost、gost-crypto、haval128, haval128,4、haval128,5、haval160,3、haval160,4、haval160,5、haval192,3、haval192,4、haval192,5、haval224,3、haval224,4、haval224,5、haval256,3、haval256,4、haval256,5、joaat、md2、md4、ripemd128、ripemd160、ripemd256、ripemd320、sha224、sha384、snefru、snefru256、tiger128,3、tiger128,4、tiger160,3、tiger160,4、tiger192,3、tiger192,4、whirlpool

HMAC-SHA1 HMAC-SHA256 两种加密方式

只介绍这两种方式 因工程用到所以贴出代码

//HMAC-SHA256 加密
+ (NSString *)hmac:(NSString *)plaintext withKey:(NSString *)key
{
const char *cKey  = [key cStringUsingEncoding:NSASCIIStringEncoding];

const char *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 char *buffer = (const unsigned char *)[HMACData bytes];

NSMutableString *HMAC = [NSMutableString stringWithCapacity:HMACData.length * 2];

for (int i = 0; i < HMACData.length; ++i){

[HMAC appendFormat:@"%02x", buffer[i]];

}
return HMAC;
}
// HMAC-SHA1
+ (NSString *)hmac_sha1:(NSString *)key text:(NSString *)text{
const char *cKey  = [key cStringUsingEncoding:NSUTF8StringEncoding];

const char *cData = [text cStringUsingEncoding:NSUTF8StringEncoding];

char cHMAC[CC_SHA1_DIGEST_LENGTH];

CCHmac(kCCHmacAlgSHA1, cKey, strlen(cKey), cData, strlen(cData), cHMAC);

NSData *HMAC = [[NSData alloc] initWithBytes:cHMAC length:CC_SHA1_DIGEST_LENGTH];

NSString *hash = [HMAC base64Encoding];//base64Encoding函数在NSData+Base64中定义(NSData+Base64网上有很多资源)
return hash;
}```

你可能感兴趣的:(HMAC-SHA1 HMAC-SHA256 两种加密方式)