hash a password string using SHA512 like C#

前端 未结 2 1933
后悔当初
后悔当初 2020-12-13 06:55

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 shoul

相关标签:
2条回答
  • 2020-12-13 07:47

    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;
    }
    
    0 讨论(0)
  • 2020-12-13 07:54

    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>
    
    0 讨论(0)
提交回复
热议问题