SHA1 hash of a string in iPhone Cocoa

Is there any easy way to create a SHA1 hash of an NSString using Cocoa for the iPhone? Or do I need to write my own SHA1 algorithm?

There doesn't seem to be any functionality in Cocoa to handle this sort of thing.

Thanks
Rick

Mac OS X (10.5.4)

Posted on Jul 30, 2008 7:16 PM

Reply
7 replies

Jul 31, 2008 2:58 AM in response to xsede

This snippet of code (based on one of my apps--one that just went out tonight!) uses SHA-256, which works in much the same way as SHA-1. It depends on the CommonCrypto headers.


unsigned char hashedChars[32];
CC_SHA256([inputString UTF8String],
[inputString lengthOfBytesUsingEncoding:NSUTF8StringEncoding],
hashedChars);
NSData * hashedData = [NSData dataWithBytes:hashedChars length:32];

Aug 1, 2008 9:08 AM in response to Brent Royal-Gordon

I'm trying to do the same thing, but something's not working right for me.
Trying to simulate encoding the simple "ab". hashedChars for me is size 33.

CC_SHA1([@"ab" UTF8String],
[@"ab" lengthOfBytesUsingEncoding:NSUTF8StringEncoding],
hashedChars);
hashedChars[32] = '\0';
printf("%s\n",hashedChars);

Result:

\332#aNF\232
|{ѽ\253\\234GK

Why am I getting these bogus values? Any ideas?

Sep 20, 2008 6:11 AM in response to tehbraun

SHA1 has a 160 bit result which is 20 bytes, SHA256 has a 256 bit result which is 32 bytes. Also the result is 8 bit unsigned chars so you must print them as data.

Hot flash from my wife: "If crypto was easy everyone would be doing it." Well she is wrong! Everyone is doing it--but badly.

Message was edited by: dgrassi, add wife's comment.

This thread has been closed by the system or the community team. You may vote for any posts you find helpful, or search the Community for additional answers.

SHA1 hash of a string in iPhone Cocoa

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple Account.