简体   繁体   中英

Printing NSString from NSData & comparing HMAC hashes

I have a NSData which I hashed using HMAC algorithm. I wanted to print the resulted string & see how it looks but all the time I am getting (null) printed on the screen. I tried 2 methods but they did not work. Can someone suggest how to print the hashed data string? I wanted to compare the hash created this way with hash created on server which is JAVA. Now, JAVA returns a string object. How will that be compared with NSData created by objective C.

NSData *hmac = [aData HMACWithAlgorithm:kCCHmacAlgSHA1];
NSString *hmacStr = [NSString stringWithUTF8String:[hmac bytes]];
NSString *hmacStr1 = [[NSString alloc] initWithData:hmac
                                                encoding:NSUTF8StringEncoding];
NSLog(@"Hashed Data=%@ data2=%@",hmacStr,hmacStr1);

I believe the problem here is that HMACWithAlogorithm: is returning the raw bytes that make up the digest rather than the bytes that make up the string UTF8 encoding of the digest. This is based on an assumption that HMACWithAlgorithm : is using CCHmac from the CommmonCrypto library under the hood.

I think the following might do what you want, it will take the raw digest returned and convert it to a hex encoded NSString of the digest:

NSData *hmac = [aData HMACWithAlgorithm:kCCHmacAlgSHA1];

// Get a pointer to the raw bytes of the digest
unsigned char *digest = (unsigned char *)[hmac bytes];

// Convert the bytes to their hex representation
NSString *hmacStr = [NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
                digest[0], digest[1], digest[2], digest[3], digest[4], digest[5], digest[6], digest[7],
                digest[8], digest[9], digest[10], digest[11], digest[12], digest[13], digest[14], digest[15],
                digest[16], digest[17], digest[18], digest[19]];      


NSLog(@"Hashed Data=%@",hmacStr);

Your second idea (hmacStr1) is fine. If that string is null, then it casts doubt on your input data.

See what happens when you do this:

NSLog(@"about to hash %@, which is %d bytes long", aData, [aData length]);
NSData *hmac = [aData HMACWithAlgorithm:kCCHmacAlgSHA1];
NSLog(@"the hash result is %@, which is %d bytes long", hmac, [hmac length]);

Null data, right? The fix needs to happen before the conversion to string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM