Hashing a string using SHA1

February 27th, 2012
#hashing

The other day I was looking around for a code snippet for hashing a string using SHA1 but couldn't find one so.....

- (NSString *)generateHashValueForString:(NSString *)toBeHashed
{
    NSString *hashedString = nil;

    NSString *stringToBeHashed = [NSString stringWithFormat:@"%@%@", toBeHashed, SALT]; //SALT is a NSString #define elsewhere

    unsigned char digest[CC_SHA1_DIGEST_LENGTH];

    NSData *stringBytes = [stringToBeHashed dataUsingEncoding:NSASCIIStringEncoding];
    if (CC_SHA1([stringBytes bytes], [stringBytes length], digest)) {

        hashedString = [[[NSString alloc] initWithBytes:digest length:sizeof(digest) encoding:NSASCIIStringEncoding] autorelease];

    }

    return hashedString;

}

What do you think? Let me know by getting in touch on Twitter - @wibosco