Trying to Write NSString sha1 function, but it's returning null

iphone, nsdata, nsstring, objective-c, sha1

Solution

Short answer: turn on gcc warnings (-Wall).

Long answer:

NSMutableData *dataToHash = [[NSMutableData alloc] init];
[dataToHash appendData:[str dataUsingEncoding:NSUTF8StringEncoding]];

is broken: You try to use a C string where an NSData argument is expected. Use

NSMutableData *dataToHash = [str dataUsingEncoding:NSUTF8StringEncoding];

instead.

The rest of the method takes the SHA1 buffer and tries interpret this data as an UTF-8 C string, which might crash or give any unexpected result. First, the buffer is not a UTF-8 string. Secondly, it's not null terminated.

What you want is to convert the SHA1 to a base 64 or similar string. Here's a nice post about how to do that.

Problem

I have the following Objective-C function: ``` +(NSString *)stringToSha1:(NSString *)str{ NSMutableData *dataToHash = [[NSMutableData alloc] init]; [dataToHash appendData:[str dataUsingEncoding:NSUTF8StringEncoding]]; unsigned char hashBytes[CC_SHA1_DIGEST_LENGTH]; CC_SHA1([dataToHash bytes], [dataToHash length], hashBytes); NSData *encodedData = [NSData dataWithBytes:hashBytes length:CC_SHA1_DIGEST_LENGTH]; [dataToHash release]; NSString *encodedStr = [NSString stringWithUTF8String:[encodedData bytes]]; //NSString *encodedStr = [[NSString alloc] initWithBytes:[encodedData bytes] // length:[encodedData length] encoding: NSUTF8StringEncoding]; NSLog(@"String is %@", encodedStr); return encodedStr; } ``` What I'm trying to do is take an NSString and SHA1 encode it. That part seems to be working, I think where I am falling over is in how to convert the NSData object back to a legible string. If I use UTF8 encoding I get blank, if I say ASCII I get weird characters. What I really want is the hex string, but I have no idea how to get it. This is using the iPhone 3.0 SDK. At the moment any String I pass in comes back out NULL.

Original source