NSString MD5 with hash

回眸只為那壹抹淺笑 提交于 2019-12-12 01:45:52

问题


Hi have to perform a login via web service sending username and password. The problem is that the server wants a strange MD5 format of password and I can't generate it.

Example

NSString password = @".";
NSString md5 = @"5058f1af8388633f609cadb75a75dc9d";

Server MD5 is "PXñ¯ƒˆc?`œ­·ZuÜ".

I need to transform 5058f1af8388633f609cadb75a75dc9d in "PXñ¯ƒˆc?`œ­·ZuÜ", but I have no ideas.

Edit

I've discovered that the result is an hash of 5058f1af8388633f609cadb75a75dc9d string.This is the .NET code on server:

byte[] passwordBytesEnc = UTF8Encoding.Default.GetBytes(".");
byte[] passwordBytesHash = MD5.Create().ComputeHash(passwordBytesEnc);
string passwordCriptata = UTF8Encoding.Default.GetString(passwordBytesHash);

回答1:


try this..

- (NSString *)MD5String:(NSString *)string{
    const char *cstr = [string UTF8String];
    NSLog(@"%s",cstr);
    unsigned char result[16];
    CC_MD5(cstr, strlen(cstr), result);
    NSLog(@"%s",result);

    return [NSString stringWithFormat:
            @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}

and call like this

NSString *md5 = @"5058f1af8388633f609cadb75a75dc9d";
    [self MD5String:md5];



回答2:


Well, what your Server expects is the String-representation of the MD5-Hex value (for whatever reason...).

You can convert your Hex-Value to a String like so:

NSString *string = @"5058f1af8388633f609cadb75a75dc9d";
NSMutableString * newString = [[NSMutableString alloc] init]; //will contain your result-string
int i = 0;
while (i < [string length])
{
    NSString * hexChar = [string substringWithRange: NSMakeRange(i, 2)];
    int value = 0;
    sscanf([hexChar cStringUsingEncoding:NSASCIIStringEncoding], "%x", &value);
    [newString appendFormat:@"%c", (char)value];
    i+=2;
}

(--> How to convert HEX to NSString in Objective-C?)



来源:https://stackoverflow.com/questions/23538573/nsstring-md5-with-hash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!