danialmoghaddam
danialmoghaddam

Reputation: 443

Encryption into a 32-bit string in Unicode (UCS-16) format by MD5 algorithm

I have this code to generate MD5 Hash in UTF-8 format :

const char* str = [clearPassword  UTF8String];
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5(str, strlen(str), result);

NSMutableString *ret = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH*2];
for(int i = 0; i<CC_MD5_DIGEST_LENGTH; i++) {
    [ret appendFormat:@"%02x",result[i]];
}

return ret;

But my requirement needs to have 32-bit Unicode Hash.

lets say the string is "admin". using my code, I'll have "21232f297a57a5a743894a0e4a801fc3" which is wrong.

I used some online generators to get unicode hash and I got "19a2854144b63a8f7617a6f225019b12" which exactly what I want.

Which part of my code needs to be changed?

Upvotes: 0

Views: 652

Answers (1)

Wevah
Wevah

Reputation: 28242

Try this:

NSData *utf16data = [clearPassword dataUsingEncoding:NSUTF16LittleEndianStringEncoding];
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5([utf16data bytes], [utf16data length], result);


NSMutableString *ret = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH*2];
for(int i = 0; i<CC_MD5_DIGEST_LENGTH; i++) {
    [ret appendFormat:@"%02x",result[i]];
}

return ret;

Upvotes: 1

Related Questions