iOS上的HMAC SHA 384

时间:2013-12-12 19:21:30

标签: ios objective-c hmac

我的代码看起来像这样(使用CommonCrypto / CommonHMAC.h):

- (NSString*) preperingCryptedData: (NSString*) data withKey: (NSString*) key {

    NSData* dataToHash = [data dataUsingEncoding:NSUTF8StringEncoding];

    NSData* keyData = [key dataUsingEncoding:NSUTF8StringEncoding];

    NSLog(@"Utility: preperingCryptedData - Data to Crypt: %@ and key %@\n...\n...\n...\n",dataToHash,keyData);

    NSMutableData *dataHash = [NSMutableData dataWithLength:CC_SHA384_DIGEST_LENGTH];

    CCHmac(kCCHmacAlgSHA384, keyData.bytes, keyData.length, dataToHash.bytes, dataToHash.length, dataHash.mutableBytes);

    NSString* readyString = [[NSString alloc] initWithData:dataToHash encoding:NSUTF8StringEncoding];

    NSLog(@"Utility: preperingCryptedData call, result :%@\n...\n...\n...\n",readyString);

    return readyString;
}

当我使用以下代码时:Here我在没有Key的情况下解码了我的字符串。我究竟做错了什么?如何在没有密钥的情况下对消息进行编码?

2 个答案:

答案 0 :(得分:5)

代码存在两个问题:

1)您使用dataToHash作为输出,而不是dataHash

2)dataHash不是UTF8数据表示,因此无法成功转换为NSString

答案 1 :(得分:0)

同意接受的答案。提供工作代码。

 - (NSString *)sha384:(NSString*)data withKey:(NSString *)key {

    NSData* dataToHash = [data dataUsingEncoding:NSUTF8StringEncoding];
    NSData* keyData = [key dataUsingEncoding:NSUTF8StringEncoding];

    unsigned char digest[CC_SHA384_DIGEST_LENGTH];

    CCHmac(kCCHmacAlgSHA384, keyData.bytes, keyData.length, dataToHash.bytes, dataToHash.length, digest);

    NSString *sha384Str;
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA384_DIGEST_LENGTH * 2];
    for(int i = 0; i < CC_SHA384_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", digest[i]];
    sha384Str = output;
    return sha384Str;
}