Bart Jacobs
Bart Jacobs

Reputation: 9082

NSData to NSString after CC_SHA1

Based on this question I wrote a category on NSString to hash NSString instances using SHA1. However, there is something wrong with my implementation. The funny thing is that logging the NSData instance does give the expected hash, but when I want to create an NSString from that NSData instance, I simply 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!

Upvotes: 3

Views: 2042

Answers (1)

Ben Zotto
Ben Zotto

Reputation: 70998

The output of a hash function is just a bare bunch of bytes. You're taking those bytes, and essentially telling NSString that they represent a UTF8-encoded string, which they don't. The resulting NSString is just garbage.

It sounds like what you really want is something like a string of hexadecimal digits that represent the hash value? If so, I believe you'll need to roll this yourself by looping through the dataFromDigest one byte at a time and outputting into a new NSMutableString the right hex digits depending on the byte's value. You can do it yourself or use some code from the web. The comment on this post looks promising.

Upvotes: 5

Related Questions