home » blog » SHA1 Encrypt Function for the iPhone (Objective-C)

Closer is Better >> Nearsoft Blog

Jesus Guerra

SHA1 Encrypt Function for the iPhone (Objective-C)

Posted by Jesus Guerra on 04/25/2011 in SHA1 , Objective-C , iPhone , iOS , encryption

Here is a little function that I found on the Web that I want share it with you.

First you need access the CommonCrypto library, so include the line below in your .h file,
#import <CommonCrypto/CommonDigest.h>

Then add the method below to the .m file.  It accepts a string and returns it as a SHA1 string.
-(NSString*) digest:(NSString*)input
{
  NSData *data = [input dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
  uint8_t digest[CC_SHA1_DIGEST_LENGTH];
  CC_SHA1(data.bytes, data.length, digest);
  NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
  for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
    [output appendFormat:@"02x", digest[i]];
  return output;
}

That's it!  I hope this helps.

TweetBacks (Tweet this post)

Trackback(0)

TrackBack URI for this entry

Comments (1)


Show/hide comments
sha-1 is hashing, not encryption.
0
The difference between encryption and hashing is, what you encrypt, you can decrypt to get the original value. What you hash, you cannot un-hash to get the original value.

So, you would hash a user's password and store that hashed value. When the user authenticates, hash his password and compare it to the stored (gibberish) value. If they match, he used the right password. You would encrypt a credit card number, as you would need to re-use that value for future purchases.
jack mama , 03/22/2012 18:32:10

Write comment

smaller | bigger

busy