2

我正在做 HMAC-SHA256 编码。试过但没有找到任何解决方案。

#include <CommonCrypto/CommonHMAC.h>

- (NSString *)hmacWithKey:(NSString *)key andData:(NSString *)data
{
const char *cKey  = [key cStringUsingEncoding:NSASCIIStringEncoding];
const char *cData = [data cStringUsingEncoding:NSASCIIStringEncoding];
unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];

///////////////////////////////////////////////////////////////
////but on below line of code i am getting EXC_BAD_ACCESS//////
///////////////////////////////////////////////////////////////

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

//////////////////////////////////////////////

NSData *out = [NSData dataWithBytes:cHMAC length:CC_SHA256_DIGEST_LENGTH];

// description converts to hex but puts <> around it and spaces every 4 bytes
NSString *hash = [out description];
hash = [hash stringByReplacingOccurrencesOfString:@" " withString:@""];
hash = [hash stringByReplacingOccurrencesOfString:@"<" withString:@""];
hash = [hash stringByReplacingOccurrencesOfString:@">" withString:@""];
// hash is now a string with just the 40char hash value in it
NSLog(@"%@",hash);
return hash;
}

请告诉我我在这里做错了什么。谢谢

4

2 回答 2

9

cStringUsingEncoding:NSASCIIStringEncodingNULL如果字符串包含非 ASCII 字符,则可以返回。因此,您应该检查 ifcKey == NULLcData == NULL

或者更好的是,转换为 UTF-8 字符串:

const char *cKey  = [key UTF8String];
const char *cData = [data UTF8String];
于 2013-11-10T09:04:11.193 回答
1

我用没有错误的示例字符串运行了 OPs 代码,因此错误必须在输入中。一个或多个输入为 nil 或非 ascii。

请提供失败的示例输入。

顺便说一句,没有必要使用 char 字符串,这里是使用 NSData 的示例:

NSData *cKey  = [key  dataUsingEncoding:NSUTF8StringEncoding];
NSData *cData = [data dataUsingEncoding:NSUTF8StringEncoding];
NSMutableData *out = [NSMutableData dataWithLength:CC_SHA256_DIGEST_LENGTH];

CCHmac(kCCHmacAlgSHA256, cKey.bytes, cKey.length, cData.bytes, cData.length, out.mutableBytes);
NSLog(@"out: %@", out);
于 2013-11-10T12:33:18.860 回答