相当于PHP函数hash()和iOS的rawoutput

时间:2015-08-11 12:32:50

标签: php objective-c hash sha512

我试图为iOS找到相应的此功能:

hash('sha512', '123', true);

这是我使用的方法,相当于:hash('sha512', '123', false);

- (NSString *)sha512{

    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
    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;
}

我怎么能让它给我rawoutput?

2 个答案:

答案 0 :(得分:2)

如果你想要NSData输出(它是原始字节的包装器:

//每个OP请求NSString上的类别

- (NSData *)sha512 {
    NSData *dataIn = [self dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableData *macOut = [NSMutableData dataWithLength:CC_SHA512_DIGEST_LENGTH];

    CC_SHA512( dataIn.bytes,
              (CC_LONG)dataIn.length,
              macOut.mutableBytes);

    return macOut;
}

测试:

NSData *sha512Data = [@"123" sha512];
NSLog(@"sha512Data: %@", sha512Data);

输出(以十六进制显示,因为这是NSData显示它的字节:

  

sha512Data:&lt; 3c9909af ec25354d 551dae21 590bb26e 38d53f21 73b8d3dc 3eee4c04 7e7ab1c1 eb8b8510 3e3be7ba 613b31bb 5c9c3621 4dc9f14a 42fd7a2f db84856b ca5c44c2&gt;

如果需要指向字节的指针,只需使用sha512Data.bytes

答案 1 :(得分:0)

这正是我想要完成的事情,希望这对遇到同样问题的人有所帮助。

How to use WSSE in iOS with salted sha512 with more than 1 iteration

- (NSString *)hashPassword:(NSString *)password ansSalt:(NSString *)salt {

    NSString *passwordSalted = [NSString stringWithFormat:@"%@{%@}",password,salt];

    NSData *passwordData = [passwordSalted dataUsingEncoding:NSUTF8StringEncoding];

    uint8_t hash[CC_SHA512_DIGEST_LENGTH];
    CC_SHA512([passwordData bytes], [passwordData length], hash);

    NSMutableData *allData = [[NSMutableData alloc] init];
    [allData appendBytes:hash length:CC_SHA512_DIGEST_LENGTH];

    for (NSInteger i = 1; i < 1000; i++) {

        [allData appendBytes:[passwordData bytes] length:[passwordData length]];
        uint8_t hashLoop[CC_SHA512_DIGEST_LENGTH];
        CC_SHA512([allData bytes], [allData length], hashLoop);
        [allData setLength:0];
        [allData appendBytes:hashLoop length:CC_SHA512_DIGEST_LENGTH];

    }

    NSData *imageData = [NSData dataWithBytes:[allData bytes] length:[allData length]];

    return [imageData base64EncodedStringWithOptions:0];

}