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.
This is what I ended up with, the next step would be to convert it to be a Category of NSString instead of a static method in a helper class:
My version of SHA1 function (simplier):
And MD5:
glycol, You will need to define your CC_SHA1_DIGEST_LENGTH constant, probably to 20, as that's the length of an SHA-1 digest according to the NIST spec at http://www.itl.nist.gov/fipspubs/fip180-1.htm
Short answer: turn on gcc warnings (-Wall).
Long answer:
is broken: You try to use a C string where an NSData argument is expected. Use
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.