NSData for NSString after CC_SHA1

Based on this question , I wrote in the category of copies NSStringto hash NSString, using SHA1. However, something is wrong with my implementation. The funny thing is that registering an NSData instance gives the expected hash, but when I want to create an NSString from that NSData instance, I just get null.

- (NSString *)sha1 {
    NSData *dataFromString = [self dataUsingEncoding:NSUTF8StringEncoding];
    unsigned char hashed[CC_SHA1_DIGEST_LENGTH];

    if ( CC_SHA1([dataFromString bytes], [dataFromString length], hashed) ) {
        NSData *dataFromDigest = [NSData dataWithBytes:hashed length:CC_SHA1_DIGEST_LENGTH];

        NSString *result = [[NSString alloc] initWithBytes:[dataFromDigest bytes] length:[dataFromDigest length] encoding:NSUTF8StringEncoding];

        return result;

    } else {

        return nil;
    }
}

Thanks for the help!

+3
source share
1 answer

The output of the hash function is just an empty byte. You take these bytes and essentially tell NSString that they represent a UTF8 encoded string, which they are not. As a result, NSString is just garbage.

, - , -? , , , dataFromDigest NSMutableString . - . .

+5

Source: https://habr.com/ru/post/1783110/


All Articles