将Java代码转换为目标C的麻烦

时间:2018-10-02 06:24:01

标签: java 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));
        }

我已经达到了那点

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];

但是不知道我是在正确的道路上进行。 我需要将密码转换为md5

1 个答案:

答案 0 :(得分:1)

尝试以下操作:

#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];
}

或如果没有密钥,请使用以下命令: How do I create an MD5 Hash of a string in Cocoa?