简体   繁体   中英

SHA256 key generator in iphone

I want to generate a key using SHA256 with N number of iterations.

They input should be my + +

I have seen the Crypto sample provided by apple but it seems it doesn't provide my requirement(or might be possible I didnt get it properly).

I have gone through below link as well but is doesnt have method to generate a key using SHA256 http://iphonedevelopment.blogspot.com/2009/02/strong-encryption-for-cocoa-cocoa-touch.html

Waiting for some hint.

Regards

Try this, it worked for me

1) To get a hash for plane 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;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM