Objective-C SHA1 Function for the iPhone
Here’s a nice little function that will generate an SHA-1 hash digest that will match what the php sha1() function will generate if you give it the same input:
#import
@implementation SHA1
+(NSString*) digest:(NSString*)input
{
const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
NSData *data = [NSData dataWithBytes:cstr length:input.length];
uint8_t digest[CC_SHA1_DIGEST_LENGTH];
CC_SHA1(data.bytes, data.length, digest);
NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
[output appendFormat:@"%02x", digest[i]];
return output;
}
@end
April 24th, 2010 at 2:13 pm
The PHP SHA1() function uses ASCII encoding. You can verify this by digesting a string containing something like “Ň” with your code, and with PHPs SHA1(). As long as your input string is guaranteed to contain only ASCII characters it will work fine.
I suggest updating the code to:
-(NSString*) digest:(NSString*)input{
NSData *data = [input dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
uint8_t digest[CC_SHA1_DIGEST_LENGTH];
CC_SHA1(data.bytes, data.length, digest);
NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
[output appendFormat:@"%02x", digest[i]];
return output;
}