简体   繁体   中英

Hashes in Cocoa and Objective-C

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.

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.)

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.

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

#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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM