Skip to content

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 <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

  1. Mark Lorenz | April 24, 2010 at 2:13 pm | Permalink

    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;
    }

  2. Andreas | September 14, 2010 at 4:23 am | Permalink

    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.

  3. admin | September 14, 2010 at 9:27 am | Permalink

    CC_SHA1_DIGEST_LENGTH is defined in CommonDigest.h. Make sure you’ve included this first line:
    #import <CommonCrypto/CommonDigest.h>

  4. Robert | August 15, 2011 at 12:14 pm | Permalink

    Thank you very much!! :)

{ 2 } Trackbacks

  1. [...] 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 [...]

  2. [...] From : http://spitzkoff.com/craig/?p=122 [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *