Generate SHA256 Hash in Objective-C

So, I need to generate a Sha256 password in Objective-C, and I cannot figure out how to do this! Is there something easy I'm just missing?

I tried to implement the following method (which was written for the iPhone, but I thought maybe it will work cross-platform, as Objective-C code does)

-(NSString*)sha256HashFor:(NSString*)input { const char* str = [input UTF8String]; unsigned char result[CC_SHA256_DIGEST_LENGTH]; CC_SHA256(str, strlen(str), result); NSMutableString *ret = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH*2]; for(int i = 0; i<CC_SHA256_DIGEST_LENGTH; i++) { [ret appendFormat:@"%02x",result[i]]; } return ret; } 

But it just spat out errors that CC_SHA256_DIGEST_LENGTH is an undeclared identifier.

+11
passwords objective-c encryption password-hash macos sha256
source share
4 answers

You need to include the appropriate header file:

 #include <CommonCrypto/CommonDigest.h> 

According to the Cryptographic Services documentation, this should be available for both iOS and OS X.

In OS X version 10.5 and later and iOS 5.0 and later, Common Crypto provides low-level C support for encryption and decryption. Common Crypto is not as simple as Security Transforms, but it provides a wider range of functions, including additional hash schemes, encryption modes, etc.

+18
source share
 #import <CommonCrypto/CommonDigest.h> 

Objective-C: SHA256 are just two lines:

 + (NSData *)doSha256:(NSData *)dataIn { NSMutableData *macOut = [NSMutableData dataWithLength:CC_SHA256_DIGEST_LENGTH]; CC_SHA256(dataIn.bytes, dataIn.length, macOut.mutableBytes); return macOut; } 

Swift 3

 func sha256Hex(string: String) -> String? { guard let messageData = string.data(using:String.Encoding.utf8) else { return nil } var digestData = Data(count: Int(CC_SHA256_DIGEST_LENGTH)) _ = digestData.withUnsafeMutableBytes {digestBytes in messageData.withUnsafeBytes {messageBytes in CC_SHA256(messageBytes, CC_LONG(messageData.count), digestBytes) } } return digestData.map { String(format: "%02hhx", $0) }.joined() } 

//Test

 let sha256HexString = sha256Hex(string:"Hello") print("sha256HexString: \(sha256HexString!)") 

sha256HexString: "185f8db32271fe25f561a6fc938b2e264306ec304eda518007d1764826381969"

+9
source share

Check out the NSHash cocoa module. It has many different hashing methods, including SHA256.

https://github.com/jerolimov/NSHash

+1
source share

A modified version of @zaph's answer in Objective-C with NSString as input and output:

 -(NSString*)sha256HashFor:(NSString*)input { NSData* data = [input dataUsingEncoding:NSUTF8StringEncoding]; NSMutableData *sha256Data = [NSMutableData dataWithLength:CC_SHA256_DIGEST_LENGTH]; CC_SHA256([data bytes], (CC_LONG)[data length], [sha256Data mutableBytes]); return [sha256Data base64EncodedStringWithOptions:0]; } 
0
source share

All Articles