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

后端 未结 6 1947
臣服心动
臣服心动 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:11

    I cleaned up https://stackoverflow.com/a/13199111/1254812 a bit and structured it as an NSString extension

    @interface NSString (SHA2HEX)
    
    /*
     Get the SHA2 (256 bit) digest as a hex string.
     */
    @property (nonatomic, readonly) NSString* sha2hex;
    @end
    
    @implementation NSString (SHA2HEX)
    
    - (NSString*)sha2hex
    {
        NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
    
        if (data.length > UINT32_MAX)
            return nil;
    
        uint8_t digest[CC_SHA256_DIGEST_LENGTH];
        CC_SHA256(data.bytes, (CC_LONG)data.length, digest);
    
        const int hexlen = CC_SHA256_DIGEST_LENGTH * 2;
        NSMutableString *hexstr = [NSMutableString stringWithCapacity:hexlen];
    
        for (int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) {
            [hexstr appendFormat:@"%02x", digest[i]];
        }
    
        return hexstr;
    }
    
    @end
    

提交回复
热议问题