hash a password string using SHA512 like C#

人盡茶涼 提交于 2019-11-30 06:22:14

问题


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#


回答1:


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>



回答2:


I am using this one.

It matches PHP SHA512 algorithm output:

<?php `hash('sha512', 'The quick brown fox jumped over the lazy dog.');` ?>


Objective-C code:

+(NSString *)createSHA512:(NSString *)string
{
    const char *cstr = [string cStringUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [NSData dataWithBytes:cstr length:string.length];
    uint8_t digest[CC_SHA512_DIGEST_LENGTH];
    CC_SHA512(data.bytes, data.length, digest);
    NSMutableString* output = [NSMutableString  stringWithCapacity:CC_SHA512_DIGEST_LENGTH * 2];

    for(int i = 0; i < CC_SHA512_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", digest[i]];
    return output;
}


来源:https://stackoverflow.com/questions/3829068/hash-a-password-string-using-sha512-like-c-sharp

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