Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I hash a NSString to SHA512

I have one quick question... I am building a social media network site app and I need to hash the password NSString. How would I accomplish this? I have the password field on the app and would like to hash the string and encode it in SHA512 for the POST request. Thanks in advance, TechnologyGuy

like image 717
TechnologyGuy Avatar asked Feb 13 '23 09:02

TechnologyGuy


1 Answers

Already answered: hash a password string using SHA512 like C#

But here's the copy-pasted code:

#include <CommonCrypto/CommonDigest.h>
+ (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];
}

Or if you prefer a hashed output, try this:

+(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;
}
like image 135
B.R.W. Avatar answered Feb 16 '23 03:02

B.R.W.