TechnologyGuy
TechnologyGuy

Reputation: 141

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

Upvotes: 4

Views: 6320

Answers (2)

duci9y
duci9y

Reputation: 4168

+ (NSData *)sha512:(NSData *)data {
    unsigned char hash[CC_SHA512_DIGEST_LENGTH];
    if ( CC_SHA512([data bytes], [data length], hash) ) {
        NSData *sha1 = [NSData dataWithBytes:hash length:CC_SHA512_DIGEST_LENGTH];        
        return sha1;
    }
return nil;
}

Put this in a category on NSData, or use it whatever way you like, the code remains the same.

You should've researched your question. I found an answer in one google search.

Upvotes: 0

B.R.W.
B.R.W.

Reputation: 1566

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;
}

Upvotes: 8

Related Questions