K.Bek
K.Bek

Reputation: 3

Troubles with converting java code to objective C

MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        String resultPassword = dc.profile.sipUsername + ":" + dc.profile.stunServer + ":" + passwd;
        md.update(resultPassword.getBytes());

        byte byteData[] = md.digest();

        StringBuffer sb = new StringBuffer();
        for (int j = 0; j < byteData.length; j++) {
            sb.append(Integer.toString((byteData[j] & 0xff) + 0x100, 16).substring(1));
        }

I have reached to that point

NSData *data = [resultPassword dataUsingEncoding:NSUTF16LittleEndianStringEncoding allowLossyConversion:NO];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5(data.bytes, data.length, digest);
    NSData *hashData = [[NSData alloc] initWithBytes:digest length: sizeof digest];

But don't know am i going on right way. I need to convert password to md5

Upvotes: 0

Views: 59

Answers (1)

ivion
ivion

Reputation: 567

Try the following:

#import <CommonCrypto/CommonHMAC.h>

NSString *calcMD5(NSString *aString, NSString *key)
{
    const char *cKey  = [key cStringUsingEncoding: NSUTF8StringEncoding];
    const char *cData = [aString cStringUsingEncoding: NSUTF8StringEncoding];

    // Berechnung der MD5-Signatur
    unsigned char cHMAC[CC_MD5_DIGEST_LENGTH];
    CCHmac(kCCHmacAlgMD5, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
    NSData *HMAC = [[NSData alloc] initWithBytes:cHMAC
                                          length:sizeof(cHMAC)];

    // Base64 encoded zurückliefern
    return [HMAC base64EncodedStringWithOptions:0];
}

Or use the following if there is no key: How do I create an MD5 Hash of a string in Cocoa?

Upvotes: 1

Related Questions