2013-12-12 62 views
1

我的代碼如下所示(使用CommonCrypto/CommonHMAC.h):HMAC SHA 384在iOS

- (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我得到了我的字符串解碼,而不關鍵。我究竟做錯了什麼?如何在沒有密鑰的情況下對消息進行編碼?

回答

5

有兩個問題與代碼:

1)您使用的dataToHash作爲輸出,而不是dataHash

2)dataHash不是UTF8數據表示,因此無法成功轉換爲NSString

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; 
}