Reinder de Vries
Reinder de Vries

Reputation: 522

How to capture NSData with SHA1 hash in NSString?

I'm having trouble computing a SHA1 hash from a string and then putting it back in another string. Here's what I do:

unsigned char hashedChars[20];
CC_SHA1([hashElements UTF8String], [hashElements lengthOfBytesUsingEncoding:NSUTF8StringEncoding], hashedChars);
NSData *hashedData = [NSData dataWithBytes:hashedChars length:20];
NSString *hash = [[NSString alloc] initWithData:hashedData encoding:NSUTF8StringEncoding];
NSLog(@"%s", hash);

The result of the log is (null). I basically make a string by combining a few strings, then try to calculate the hash, which is stored in an NSData object and then retrieved and put back in the hash string. When I log hashedData, I can clearly see a result coming up - which appears to be correct. That should indicate that something goes wrong on the fourth line. But what? Any help is greatly appreciated.

Kind regards,

Reinder

Upvotes: 2

Views: 1412

Answers (1)

Costique
Costique

Reputation: 23722

SHA-1 is a 20-bytes binary chunk, not a valid UTF-8 string. This is why NSString's initWithData:encoding: fails. What is commonly used for a representation of hash sums is a HEX string. Basically, what you need is [hashedData description].

Upvotes: 3

Related Questions