Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
408 views
in Technique[技术] by (71.8m points)

iphone - hash a password string using SHA512 like C#

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#

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...