SHA1 encryption in iOS

The code in this post is adapted from a StackOverflow post. The original returned an MD5 encrypted string. This one returns a SHA1 encryption identical to using

sha1();

in PHP.

SHA1 Encryption in iOS

First you need to import CommonCrypto into your class header file.

#import <CommonCrypto/CommonDigest.h>

Next within your .m file add the following method:

- (NSString *)sha1:(NSString *)str {
        const char *cStr = [str UTF8String];
unsigned char result[CC_SHA512_DIGEST_LENGTH];
     CC_SHA1(cStr, strlen(cStr), result);
    if (result) {
    /* SHA-1 hash has been calculated and stored in 'result'. */

NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH];
     
        for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
            [output appendFormat:@"%02x", result[i]];
        return output;

}
    return nil;
}

see here for an explanation of the %02x. It is also used here by Apple in the construction of hexadecimal strings.

Testing

Finally, call the method in the following way:

NSLog(@"SHA1: %@",[self sha1:@"Hello World"]);

Using HyperEdit, MAMP or similar, compare the result to:

<?php echo sha1("Hello World"); ?>


Endorse on Coderwall

Comments