본문 바로가기

iPhone dev./Objective C general

Objective C 에서 sha512 사용하기

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.

(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;
}
출처 : 
http://stackoverflow.com/questions/3829068/hash-a-password-string-using-sha512-like-c-sharp