How can I compute a SHA-2 (ideally SHA 256 or SHA 512) hash in iOS?

后端 未结 6 1944
臣服心动
臣服心动 2020-11-27 10:32

The Security services API doesn\'t appear to allow me to compute a hash directly. There are plenty of public domain and liberally licensed versions available, but I\'d rathe

6条回答
  •  离开以前
    2020-11-27 11:19

    Here's a pretty similar one based on NSString

    + (NSString *)hashed_string:(NSString *)input
    {
        const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
        NSData *data = [NSData dataWithBytes:cstr length:input.length];
        uint8_t digest[CC_SHA256_DIGEST_LENGTH];
    
        // This is an iOS5-specific method.
        // It takes in the data, how much data, and then output format, which in this case is an int array.
        CC_SHA256(data.bytes, data.length, digest);
    
        NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2];
    
        // Parse through the CC_SHA256 results (stored inside of digest[]).
        for(int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) {
            [output appendFormat:@"%02x", digest[i]];
        }
    
        return output;
    }
    

    (Credits go to http://www.raywenderlich.com/6475/basic-security-in-ios-5-tutorial-part-1)

提交回复
热议问题