Sha256 in Objective-C for iPhone

18,534

Solution 1

Try this, it worked for me

1) To get a hash for plain text input

-(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;
}

2) To get hash for NSData as input

Note:- I have used NSData category, so the code is as follow

    - (NSString *)SHA256_HASH {
    //if (!self) return nil;

    unsigned char hash[CC_SHA256_DIGEST_LENGTH];
    if ( CC_SHA256([(NSData*)self bytes], [(NSData*)self length], hash) ) {
        NSData *sha2 = [NSData dataWithBytes:hash length:CC_SHA256_DIGEST_LENGTH]; 

        // description converts to hex but puts <> around it and spaces every 4 bytes
        NSString *hash = [sha2 description];
        hash = [hash stringByReplacingOccurrencesOfString:@" " withString:@""];
        hash = [hash stringByReplacingOccurrencesOfString:@"<" withString:@""];
        hash = [hash stringByReplacingOccurrencesOfString:@">" withString:@""];
        // hash is now a string with just the 40char hash value in it
        //NSLog(@"hash = %@",hash);

        // Format SHA256 fingerprint like
        // 00:00:00:00:00:00:00:00:00
        int keyLength=[hash length];
        NSString *formattedKey = @"";
        for (int i=0; i<keyLength; i+=2) {
            NSString *substr=[hash substringWithRange:NSMakeRange(i, 2)];
            if (i!=keyLength-2) 
                substr=[substr stringByAppendingString:@":"];
            formattedKey = [formattedKey stringByAppendingString:substr];
        }

        return formattedKey;
    }
    return nil;
}

Solution 2

It's important to know that you need to import:

#import <CommonCrypto/CommonDigest.h>

Hope this help!

Share:
18,534
pascalbros
Author by

pascalbros

Updated on June 11, 2022

Comments

  • pascalbros
    pascalbros about 2 years

    When I use this code to create a sha256 of a string

    unsigned char hashedChars[32];
    NSString *inputString;
    inputString = [NSString stringWithFormat:@"hello"];
    NSData * inputData = [inputString dataUsingEncoding:NSUTF8StringEncoding];
    CC_SHA256(inputData.bytes, inputData.length, hashedChars);
    

    It returns the hash correctly, but I need to insert a string like this \x00\x25\x53 and in this case, the function returns a sha256 of empty string because the specified encoding cannot be used to convert the receiver.

    Now, my question is:How to insert this special characters for generate a correct hash? Thanks

  • pascalbros
    pascalbros almost 14 years
    My cycle trasform for example this string "002553" in "\x00\x25\x53" and i would send this bytes to the sha256 function for create the hash, but i have problem with encoding obviously!
  • Basbous
    Basbous over 11 years
    How to make a hash for special characters like "Lähettäjä:" ??
  • Jaydeep Jadav
    Jaydeep Jadav almost 11 years
    Thanks for it! First one is working with special characters too!
  • André Fratelli
    André Fratelli over 9 years
    Slight remark, what is the if (!self) for? If the instance is nil, the signal will never get to this method, right?
  • Mr.G
    Mr.G over 8 years
    how can i use this with a key , with a key and a string ?
  • Jagadeeshwar
    Jagadeeshwar over 8 years
    @Mr.G didn't get you how exactly you want to use the SHA alg. But if it the encryption you are looking for then this doesn't help you.
  • Mr.G
    Mr.G over 8 years
    @Jagadeeshwar its like this same as hash_init('sha256',HASH_HMAC,$salt);hash_update($hash,$plain‌​_hash); in php want to do the same functionality in iOS
  • CyberMew
    CyberMew over 8 years
    What's CC_SHA256_DIGEST_LENGTH? Got it - need to #include <CommonCrypto/CommonDigest.h>
  • Scott Fister
    Scott Fister over 7 years
    If you're getting the implicit conversion error you need to change the line to this CC_SHA256(str, (CC_LONG)strlen(str), result);