MD5 in Object-C and C#
I have a method written in c# to get md5:
public static string encryptPasswordWithMd5(string password)
{
MD5 md5Hasher = MD5.Create();
byte[] data = md5Hasher.ComputeHash(Encoding.Unicode.GetBytes(password));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < data.Length; i++)
sb.Append(data[i].ToString("x2"));
return sb.ToString();
}
Now I need to implement the same function using objective-c, how to do it?
ps: I have used the way here http://discussions.apple.com/thread.jspa?threadID=1509152&tstart=96
the code in objc is
-(NSString *) encryptPasswordWithMd5: (NSStrin开发者_如何学Gog *) _password {
const char * cStr = [_password cStringUsingEncoding: NSUTF16LittleEndianStringEncoding];unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5(cStr, strlen(cStr), 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]
];
}
but they don't get the same result. take 'admin' as example, c# is "19a2854144b63a8f7617a6f225019b12" but the objc is "0CC175B9C0F1B6A831C399E269772661";
Check this links (last post). It shows how to calculate MD5 hash in Objective-C.
BTW: You can also simplify MD5 computation in C# a bit
public static string encryptPasswordWithMd5(string password)
{
var md5 = new MD5CryptoServiceProvider();
var originalBytes = ASCIIEncoding.Default.GetBytes(password);
var encodedBytes = md5.ComputeHash(originalBytes);
return BitConverter.ToString(encodedBytes);
}
精彩评论