hash a password string using SHA512 like C#

China☆狼群 提交于 2019-11-28 17:34:17
Philippe Leybaert

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>
Martynas

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