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

The security services API does not allow me to directly calculate the hash. There are many publicly available and freely licensed versions, but I would prefer to use a system library implementation, if possible.

Data is accessible via NSData or simple pointers.

The cryptographic strength of a hash is important to me. SHA-256 is the minimum allowed hash size.

+54
security ios objective-c hash sha256
Jun 03 2018-11-11T00:
source share
5 answers

This is what I use for SHA1:

+ (NSData *)sha1:(NSData *)data { unsigned char hash[CC_SHA1_DIGEST_LENGTH]; if ( CC_SHA1([data bytes], [data length], hash) ) { NSData *sha1 = [NSData dataWithBytes:hash length:CC_SHA1_DIGEST_LENGTH]; return sha1; } return nil; } 

Replace CC_SHA1 with CC_SHA256 (or whichever you need), as well as CC_SHA1_DIGEST_LENGTH with CC_SHA256_DIGEST_LENGTH .

You need #import <CommonCrypto/CommonDigest.h>

+78
Jun 03 2018-11-11T00:
source share

Here is pretty similar to 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 )

+31
Nov 02 '12 at 16:15
source share

This is what worked for me

 func sha256(securityString : String) -> String { let data = securityString.dataUsingEncoding(NSUTF8StringEncoding)! var hash = [UInt8](count: Int(CC_SHA256_DIGEST_LENGTH), repeatedValue: 0) CC_SHA256(data.bytes, CC_LONG(data.length), &hash) let output = NSMutableString(capacity: Int(CC_SHA1_DIGEST_LENGTH)) for byte in hash { output.appendFormat("%02x", byte) } return output as String } 
+3
Mar 18 '16 at 22:06
source share

Below is the link I used to create the hash value of the document, and its very simple and simple calculation of the hash value especially for large files.

Link: http://www.joel.lopes-da-silva.com/2010/09/07/compute-md5-or-sha-hash-of-large-file-efficiently-on-ios-and-mac- os-x / comment-page-1 / # comment-18533

0
Dec 12 '16 at 7:33
source share
 + (NSData *)sha256DataFromData:(NSData *)data { unsigned char result[CC_SHA256_DIGEST_LENGTH]; CC_SHA256([data bytes], (int)[data length], result); return [NSData dataWithBytes:result length:CC_SHA256_DIGEST_LENGTH]; } 
0
May 24 '17 at 16:55
source share



All Articles