Re: How to encrypt a String to a SHA-1 Encrypted in iPhone
Re: How to encrypt a String to a SHA-1 Encrypted in iPhone
- Subject: Re: How to encrypt a String to a SHA-1 Encrypted in iPhone
- From: Keith Duncan <email@hidden>
- Date: Sun, 28 Nov 2010 14:34:08 +0000
> @implementation NSData (NSDataDigestCategory)
> - (NSString *)sha1 {
> uint8_t digest[CC_SHA1_DIGEST_LENGTH];
>
> CC_SHA1([self bytes], [self length], digest);
>
> // use an uppercase X to get an uppercase hash
> NSString *hash = [NSString stringWithFormat:@"xxxxxxxxxxxxxxxxxxxx",
> digest[0], digest[1], digest[2], digest[3], digest[4], digest[5], digest[6], digest[7], digest[8], digest[9],
> digest[10], digest[11], digest[12], digest[13], digest[14], digest[15], digest[16], digest[17], digest[18], digest[19], digest[20]];
>
> // or, if you prefer:
>
> NSMutableString *hash2 = [NSMutableString stringWithCapacity:40];
> for (int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
> [hash2 appendFormat:@"x", digest[i]];
>
> return hash; // or hash2
> }
> @end
There's no such thing as an 'uppercase hash'. Technically, this doesn't return an SHA-1 hash, which would be 20 bytes of binary data, this returns a Base16 encoded SHA-1 hash, which is 40 characters in the range [0..F] (with values in the range [0b1010..0b1111] mapping to a value in the domain of either [A..F] or [a..f] which is where the 'case' comes into it).
This method should either return an NSData object of the digest bytes, and the category should include an additional method to return a base-converted NSString object representing the receiver i.e.
> @interface NSData (MyNSDataAdditions)
> - (NSData *)SHA1;
> - (NSString *)base16String;
> @end
or amend the current method name to imply that the encoding is base16 i.e.
> @interface NSData (MyNSDataAdditions)
> - (NSString *)sha1WithBase16Encoding;
> @end
Cheers,
Keith
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden