Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate the MD5 Hash of a String in Objective-C

I'm having a lot of trouble converting the following code to Objective-C, can anyone lend a hand:

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 "";
}
like image 356
Daniel Avatar asked Dec 28 '22 11:12

Daniel


1 Answers

This should work:

#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];
}      
like image 56
Jacob Relkin Avatar answered Jan 17 '23 17:01

Jacob Relkin