使用SHA512(如C#)散列密码字符串 [英] hash a password string using SHA512 like C#

查看:374
本文介绍了使用SHA512(如C#)散列密码字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的iPhone应用程序开发登录函数,所以我想使用SHA512哈希算法对密码进行哈希处理,然后将结果作为NSString(结果应该与C#中的SHA512相同)。在互联网上花了很多时间之后,我仍然没有找到解决方案! :(b / b)

有没有人有解决方案和示例代码,请帮助我!
非常感谢!



[Update]
在我的C#代码中,密码是使用SecureString存储的,所以也许这是因为在objective-c和C#之间创建不同的字节数组

解决方案

这个函数将使用SHA512对一个字符串进行散列,得到的字符串是散列的十六进制表示形式:

  +(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,摘要);

NSData * out = [NSData dataWithBytes:摘要长度:CC_SHA512_DIGEST_LENGTH];

return [out description];
}

不要忘记包含更正t header:

  #include< CommonCrypto / CommonDigest.h> 


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#

解决方案

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>

这篇关于使用SHA512(如C#)散列密码字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆