如何给Hmac SHA256目标C提供十六进制字符串?

时间:2017-03-22 16:00:59

标签: ios objective-c xcode sha256 hmac

我试图通过以下方式在目标C中生成hmac SHA256:

const char *cKey  = [key cStringUsingEncoding:NSUTF8StringEncoding];
const char *cData = [data cStringUsingEncoding:NSUTF8StringEncoding];
unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];
CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);

只要是一个字符串,这就可以正常工作。问题在于用于生成mac的外部服务器命令是:

openssl dgst -binary -sha256 -mac HMAC -macopt hexkey:$key 

hmac正在考虑将密钥作为 hexkey 生成。所以很明显hmac产生的不同。

如何告知目标C中的CCMac功能将密钥视为十六进制密钥?我已经尝试将字符串键转换为字节数组并将其传递给CCMAC但仍然无效。

在android中我通过将十六进制数转换为Big Integer然后对其执行getBytes来实现相同的目的,使用它来创建密钥。 希望你们中的一些人能够指导我。

1 个答案:

答案 0 :(得分:2)

这是你正在寻找的吗?

- (NSData *)dataFromHexString:(NSString *)sHex {
    const char *chars = [sHex UTF8String];
    int i = 0;
    NSUInteger len = sHex.length;

    NSMutableData *data = [NSMutableData dataWithCapacity:len / 2];
    char byteChars[3] = {'\0','\0','\0'};
    unsigned long wholeByte;

    while (i < len) {
        byteChars[0] = chars[i++];
        byteChars[1] = chars[i++];
        wholeByte = strtoul(byteChars, NULL, 16);
        [data appendBytes:&wholeByte length:1];
    }

    return data;
}

- (NSData *)hmacForHexKey:(NSString *)hexkey andStringData:(NSString *)data
{

    NSData *keyData = [self dataFromHexString:hexkey];

    const char *cKey  = [keyData bytes];
    const char *cData = [data cStringUsingEncoding:NSUTF8StringEncoding];

    unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];

    CCHmac(kCCHmacAlgSHA256, cKey, keyData.length, cData, strlen(cData), cHMAC);

    return [[NSData alloc] initWithBytes:cHMAC length:sizeof(cHMAC)];

}

- (NSData *)hmacForKey:(NSString *)key andStringData:(NSString *)data
{

    const char *cKey  = [key cStringUsingEncoding:NSUTF8StringEncoding];
    const char *cData = [data cStringUsingEncoding:NSUTF8StringEncoding];

    unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];

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

    return [[NSData alloc] initWithBytes:cHMAC length:sizeof(cHMAC)];

}

- (void)testIt {

    NSString *key = @"This is my random key.";
    NSString *hexKey = @"54686973206973206d792072616e646f6d206b65792e";

    NSString *data = @"This is a data string.";

    NSData *hmac1 = [self hmacForKey:key andStringData:data];
    NSLog(@"hmacForKey   : %@", hmac1);

    NSData *hmac2 = [self hmacForHexKey:hexKey andStringData:data];
    NSLog(@"hmacForHexKey: %@", hmac2);
}