Trying to Write NSString sha1 function, but it's returning null

后端 未结 4 878
有刺的猬
有刺的猬 2020-12-17 02:09

I have the following Objective-C function:

+(NSString *)stringToSha1:(NSString *)str{
    NSMutableData *dataToHash = [[NSMutableData alloc] init];
    [data         


        
4条回答
  •  鱼传尺愫
    2020-12-17 03:15

    This is what I ended up with, the next step would be to convert it to be a Category of NSString instead of a static method in a helper class:

    +(NSString *)stringToSha1:(NSString *)str{
        const char *s = [str cStringUsingEncoding:NSASCIIStringEncoding];
        NSData *keyData = [NSData dataWithBytes:s length:strlen(s)];
    
        // This is the destination
        uint8_t digest[CC_SHA1_DIGEST_LENGTH] = {0};
        // This one function does an unkeyed SHA1 hash of your hash data
        CC_SHA1(keyData.bytes, keyData.length, digest);
    
        // Now convert to NSData structure to make it usable again
        NSData *out = [NSData dataWithBytes:digest length:CC_SHA1_DIGEST_LENGTH];
        // description converts to hex but puts <> around it and spaces every 4 bytes
        NSString *hash = [out description];
        hash = [hash stringByReplacingOccurrencesOfString:@" " withString:@""];
        hash = [hash stringByReplacingOccurrencesOfString:@"<" withString:@""];
        hash = [hash stringByReplacingOccurrencesOfString:@">" withString:@""];
    
        NSLog(@"Hash is %@ for string %@", hash, str);
    
        return hash;
    }
    

提交回复
热议问题