HMAC-SHA1的Objective-C示例代码

我需要在目标C中生成HMAC-SHA1。但是我没有找到任何有效的方法。我尝试使用CCHMAC与CommonCrypto,但没有用。我需要生成一个hmac,然后生成HOTP编号。

有人在Objective C或C中有任何示例代码吗?


至尊宝的传说
浏览 791回答 3
3回答

呼如林

使用SHA-256生成HMAC的方法如下:NSString *key;NSString *data;const char *cKey  = [key cStringUsingEncoding:NSASCIIStringEncoding];const char *cData = [data cStringUsingEncoding:NSASCIIStringEncoding];unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);NSData *HMAC = [[NSData alloc] initWithBytes:cHMAC                                      length:sizeof(cHMAC)];NSString *hash = [HMAC base64Encoding];我不知道HOTP库,但是如果我没记错的话,该算法非常简单。

慕标5832272

这是一个完整的解决方案,无需任何额外的库或技巧即可工作:+(NSString *)hmac:(NSString *)plainText withKey:(NSString *)key{&nbsp; &nbsp; const char *cKey&nbsp; = [key cStringUsingEncoding:NSASCIIStringEncoding];&nbsp; &nbsp; const char *cData = [plainText cStringUsingEncoding:NSASCIIStringEncoding];&nbsp; &nbsp; unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];&nbsp; &nbsp; CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);&nbsp; &nbsp; NSData *HMACData = [[NSData alloc] initWithBytes:cHMAC length:sizeof(cHMAC)];&nbsp; &nbsp; const unsigned char *buffer = (const unsigned char *)[HMACData bytes];&nbsp; &nbsp; NSString *HMAC = [NSMutableString stringWithCapacity:HMACData.length * 2];&nbsp; &nbsp; for (int i = 0; i < HMACData.length; ++i)&nbsp; &nbsp; &nbsp; &nbsp; HMAC = [HMAC stringByAppendingFormat:@"%02lx", (unsigned long)buffer[i]];&nbsp; &nbsp; return HMAC;}您不必包含任何第三方base64库,因为它已经被编码。
打开App,查看更多内容
随时随地看视频慕课网APP