views:

505

answers:

4

Hi, I'm writing an application for Mac. I need some code which generates a hash from a string. I need to create these hashes:

  • MD2
  • MD4
  • MD5
  • SHA-0
  • SHA-1

How can I do this? Thanks.

A: 

Since Objective-C is a superset of C, you can use standard C-based OpenSSL libraries to do this. Check out the EVP_DigestInit man page to get started. Essentially, you'll call EVP_DigestInit to begin making a hash, then read data into it using EVP_DigestUpdate until you've read the entire thing.

Jeff Kelley
+5  A: 

CommonCrypto (which is part of libsystem on Mac OS X) provides everything in your list except SHA-0.

Do you really need SHA-0? (If you do not have legacy data using SHA-0, you shouldn't start using it now.)

Jim Correia
+1  A: 

OpenSSL comes with Mac OS X so you can just include its headers. e.g.:

#include <openssl/pem.h>
#include <openssl/rsa.h>
#include <openssl/bio.h>

The OpenSSL API is plain C but you could wrap the things you need in Obj-C classes. (I am sure there are already some wrappers around).

Take a look at the end of this blog post to get started: http://sigpipe.macromates.com/2004/09/05/using-openssl-for-license-keys/
The article uses OpenSSL to generate license keys for a copy protection scheme, but it offers instructions on how to use OpenSSL on Mac OS X.

weichsel
+1  A: 

I wrote this post on my blog:

http://cocoawithlove.com/2009/07/hashvalue-object-for-holding-md5-and.html

which shows a class that creates MD5 and SHA256 hashes from arbitrary data. It uses the CommonCrypto functions CC_MD5 and CC_SHA256 to perform the actual hashing. You could easily follow the same approach to include further methods that compute all of the hashes you listed.

Matt Gallagher