在Objective-C中计算字符串的MD5哈希值

时间:2011-11-02 15:09:42

标签: java objective-c hash base64 md5

我在将以下代码转换为Objective-C时遇到了很多麻烦,任何人都可以伸出援助之手:

public String encodeString(String s) {
    try {
        // Create MD5 Hash
        MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
        digest.update(s.getBytes());
        byte messageDigest[] = digest.digest();

        Base64 b = null;

        return b.encodeToString(messageDigest,1); 

    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return "";
}

1 个答案:

答案 0 :(得分:10)

这应该有效:

#import <CommonCrypto/CommonDigest.h>

- (NSString *) encodeString:(NSString *) s {
   const char *cStr = [s UTF8String];
   unsigned char result[CC_MD5_DIGEST_LENGTH];
   CC_MD5(cStr, strlen(cStr), result);
   NSMutableString *result = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
   for(int i = 0; i < CC_MD5_DIGEST_LENGTH; ++i) {
      [result appendFormat:@"%02x", result[i]];
   }       
   return [NSString stringWithString:result];
}