Last Updated: February 25, 2016
·
2.364K
· vincentsaluzzo

Create a SHA-1 method in Objective-C

First, import CommonDigest.h from CommonCrypto

#import <CommonCrypto/CommonDigest.h>

Then, paste this sample code where you need:

-(NSString*) returnHashWithSHA1:(NSString*)inputText {
    const char *cstr = [inputText cStringUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [NSData dataWithBytes:cstr length:inputText.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;
}