简体   繁体   中英

Working with SHA256 hashing on iOS

I've looked at at least 6 pages on SO about iOS and SHA256, and I still can't figure out what's going on.

Generally, I'm used to doing SHA256 in PHP with the hash() function, and it returning a string value like: db1204372d8d9f14acc608b497227047d63ad868987883d0a29198be8e6ce853

I'm trying to implement SHA256 in my iOS app in order to beef up security between the app and the server, but the encoding part is giving me a headache...

I'm using an NSData category:

+ (NSData *)sha256:(NSData *)data {

NSMutableData *out = [NSMutableData dataWithLength:CC_SHA256_DIGEST_LENGTH];

CC_SHA256(data.bytes, data.length,  out.mutableBytes);

if ( CC_SHA256(data.bytes, data.length, out.mutableBytes) ) return out;

return nil;
}

However, no matter how I try to encode the resulting NSData object into an NSString (to send to the server), I end up with a string like this ã°ÄBüûôÈo¹$'®AädL¤xR¸U

My question - how can I implement a category that behaves the same as hash , such that passing the same value to either method should yield the same value?

Thanks for the helps

Sorry that I'm very late to the party.

The result you get from php is the concatenation of the hexadecimal values of each byte. The value you got from ios is the actual byte string.

I suspect you are using something like [[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding] to get the string.

But you should convert NSData to the form you require using [data description] as described in How can i convert NSdata to hex string? .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM