Question

My code looks like this (using 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;
}

When I used code from: Here I got my string decoded without the Key. What am I doing wrong? How it's possible to encode message without the key?

Was it helpful?

Solution

There are two problem with the code:

1) You are using dataToHash as the output instead of dataHash.

2) dataHash is not a UTF8 data representation so it can not be successfully converted into a NSString.

OTHER TIPS

Agree with the accepted answer. Provide working code.

 - (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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top