Generating SHA256 in iphone/Objective C ...?

Kuldeep Singh picture Kuldeep Singh · Jan 17, 2011 · Viewed 10.8k times · Source

How to create a SHA256 of a String in iphone/objective c...

Sha256 in Objective-C for iPhone

I have read this..but i am not able to understand this..

I want to create output similar to php funcation as follows:-

$hash = hash_hmac("sha256", implode(';', $hash_parameters), $api_key);

where hash parameters is the array of arguments...

Can you write this as a method which will take the input string...?

And what will be the output of method NSData or NSString..??

I have to create a request with this..??

So in the request object..

[theRequest setHTTPBody:requestBody];

what should be the type of requestBody??

Answer

TALLBOY picture TALLBOY · Jan 26, 2011

I'm not sure I fully understand your questions but if you're looking to create a hashed string you CAN pass in your parameters as arguments to a hash function.

-(void)generateHashedString {

    NSString *key = @"Some random string";
    //enter your objects you want to encode in the data object
    NSString *data = [NSString stringWithFormat:@"%@%@%@", @"sha256", hash_parameters, api_key];

    const char *cKey  = [key cStringUsingEncoding:NSASCIIStringEncoding];
    const char *cData = [data cStringUsingEncoding:NSASCIIStringEncoding];

    unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];

    CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);

    NSData *HMAC = [[NSData alloc] initWithBytes:cHMAC
                                          length:sizeof(cHMAC)];

    NSString *hash = [HMAC base64Encoding];

}

This will give you an NSString of hash that you can use to make your requests. NSLog(@"%@",hash); To see what you generated!

Make sure you #import <CommonCrypto/CommonHMAC.h> too