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 <CommonCrypto/CommonDigest.h>
@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
{ 4 } Comments
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;
}
I’m new in programming and i have a question:
uint8_t digest[CC_SHA1_DIGEST_LENGTH];
What does CC_SHA1_DIGEST_LENGTH mean?
I will compile and it complanes this line.
CC_SHA1_DIGEST_LENGTH is defined in CommonDigest.h. Make sure you’ve included this first line:
#import <CommonCrypto/CommonDigest.h>
Thank you very much!!
{ 2 } Trackbacks
[...] le hash digest SHA1 en objective-C Je suis tombé sur cette fonction donné sur The Reluctant Blogger, cette fonction retourne le hash sha1 équivalent à la fonction php [...]
[...] From : http://spitzkoff.com/craig/?p=122 [...]
Post a Comment