Sha256 Hashes in Objective-C

Here’s the translation of the SHA256 Hashes example from Go to Objective-C:

Our first program demonstrates how to compute SHA256 hashes in Objective-C. SHA256 hashes are frequently used to compute short identities for binary or text blobs. For example, TLS/SSL certificates use SHA256 to compute a certificate’s signature.

#import <Foundation/Foundation.h>
#import <CommonCrypto/CommonDigest.h>

NSString *sha256(NSString *input) {
    const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [NSData dataWithBytes:cstr length:input.length];
    uint8_t digest[CC_SHA256_DIGEST_LENGTH];
    
    CC_SHA256(data.bytes, (CC_LONG)data.length, digest);
    
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2];
    for(int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) {
        [output appendFormat:@"%02x", digest[i]];
    }
    return output;
}

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSString *s = @"sha256 this string";
        
        NSString *hash = sha256(s);
        
        NSLog(@"%@", s);
        NSLog(@"%@", hash);
    }
    return 0;
}

In Objective-C, we use the CommonCrypto library to compute SHA256 hashes. This library is part of the iOS and macOS SDKs.

We define a helper function sha256 that takes a string input and returns its SHA256 hash as a hexadecimal string.

In the main function:

  1. We create an autorelease pool to manage memory.
  2. We define our input string.
  3. We call our sha256 function to compute the hash.
  4. We print both the original string and its hash.

To run the program, save it as a .m file (e.g., sha256_hashes.m) and compile it with:

$ clang -framework Foundation sha256_hashes.m -o sha256_hashes
$ ./sha256_hashes
sha256 this string
1af1dfa857bf1d8814fe1af8983c18080019922e557f15a8a...

This computes the hash and prints it in a human-readable hex format.

Note that if you need cryptographically secure hashes, you should carefully research hash strength!

Objective-C provides access to other hash functions through the CommonCrypto library. For example, to compute SHA512 hashes, you would use CC_SHA512 instead of CC_SHA256.