Objective-C Implicit conversion loses integer precision (size_t to CC_Long)

后端 未结 3 602
野趣味
野趣味 2021-02-12 08:11

I have a function that\'s generating a sha256 encryption of a string,

Here\'s the function:

    -(NSString*)sha256HashFor:(NSString*)input
{
    const ch         


        
相关标签:
3条回答
  • 2021-02-12 08:44
    1. Presumably that's not an error but a warning.

    2. "I just need to convert the strlen(str) to a CC_Long, but I have no idea how to do that." - explicit type conversion (type casting): (CC_LONG)strlen(str), but I don't think you really need this.

    0 讨论(0)
  • 2021-02-12 08:49

    This code will not show any warning and works perfectly.

    - (NSString*) sha256 {
        const char * pointer = [self UTF8String];
        unsigned char result[CC_SHA256_DIGEST_LENGTH];
        CC_SHA256(pointer, (CC_LONG)strlen(pointer), 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;
    }
    
    0 讨论(0)
  • 2021-02-12 09:00

    Speaking from the iOS perspective, the fact that CC_LONG (a.k.a. uint32_t) and size_t (unsigned long) are incompatible sizes can be a security/stability concern in some applications, especially when dealing with reusable library functions.

    An MD5 hash is a 128 bit hash of a potentially unlimited length message, so there is a good reason for this warning. If you truncate a length greater than 2^32, you will come up with an incorrect hash.

    Your code should logically decide on how large of a string it can support. In this case using CC_MD5, it would have to be 2^32 bytes.

    Maximum length for MD5 input/output

    0 讨论(0)
提交回复
热议问题