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
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