Generate SHA256 hash in Objective-C

garetmckinley picture garetmckinley · May 31, 2013 · Viewed 14.9k times · Source

So I need to generate a Sha256 password in Objective-C, and can't figure out for the life of me how to do it! Is there something easy I'm just missing?

I've tried implementing the following method (which was written for iPhone, but I figured maybe it'd work cross-platform, as some Objective-C code does)

-(NSString*)sha256HashFor:(NSString*)input
{
    const char* str = [input UTF8String];
    unsigned char result[CC_SHA256_DIGEST_LENGTH];
    CC_SHA256(str, strlen(str), result);

    NSMutableString *ret = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH*2];
    for(int i = 0; i<CC_SHA256_DIGEST_LENGTH; i++)
    {
        [ret appendFormat:@"%02x",result[i]];
    }
    return ret;
}

But that just spat out errors about CC_SHA256_DIGEST_LENGTH being an undeclared identifier.

Answer

James Holderness picture James Holderness · May 31, 2013

You need to include the appropriate header file:

#include <CommonCrypto/CommonDigest.h>

According to the Cryptographic Services documentation this should be available on both iOS and OS X.

In OS X v10.5 and later and iOS 5.0 and later, Common Crypto provides low-level C support for encryption and decryption. Common Crypto is not as straightforward as Security Transforms, but provides a wider range of features, including additional hashing schemes, cipher modes, and so on.