views:

48

answers:

1

Dear All,

I am developing logon function for my iPhone Application, so I want to hash the password using the SHA512 hashing algorithm then get the result as NSString (the result should be the same with SHA512 in C#). After spending a lot of time in the internet, I still not find out the solution yet! :(

Is there anyone has the solution and sample code, please help me! Thanks a lot!

[Update] In my C# code, the password is stored using SecureString, so maybe it's cause make different byte array between objective-c and C#

+2  A: 

This function will hash a string using SHA512. The resulting string is a hex representation of the hash:

+ (NSString *) createSHA512:(NSString *)source {

    const char *s = [source cStringUsingEncoding:NSASCIIStringEncoding];

    NSData *keyData = [NSData dataWithBytes:s length:strlen(s)];

    uint8_t digest[CC_SHA512_DIGEST_LENGTH] = {0};

    CC_SHA512(keyData.bytes, keyData.length, digest);

    NSData *out = [NSData dataWithBytes:digest length:CC_SHA512_DIGEST_LENGTH];

    return [out description];
}

Don't forget to include the correct header:

#include <CommonCrypto/CommonDigest.h>
Philippe Leybaert
Oh, thanks you so much, I will try it right now!
Son Nguyen
Dear Philippe, it's working well, thanks!
Son Nguyen
Dear Philippe, I have a problem that when comparing hashed passwords are different between C# and objective-c. In my C# code, I used SecureString to store password, so I have to use Marshal Copy to get byte array and I saw that there are 0bytes appended after each password's char, maybe that's cause the hashed pass are different. I don't know how to resolve it, could you please help me again? thanks!
Son Nguyen