Sha256 in Objective-C for iPhone

前端 未结 4 1313
天命终不由人
天命终不由人 2020-12-08 05:36

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

unsigned char hashedChars[32];
NSString *inputString;
inputString = [NSString stringWithFormat:@\"hello\"         


        
4条回答
  •  有刺的猬
    2020-12-08 06:26

    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

    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

提交回复
热议问题