问题
Hi is there anyone with a working SHA512 iOS implementation? The code doesn't seem to generate the same one I have on php.
<?php
$code = hash("SHA512", '123' . '123' );
echo $code;
?>
Output: 263fec58861449aacc1c328a4aff64aff4c62df4a2d50b3f207fa89b6e242c9aa778e7a8baeffef85b6ca6d2e7dc16ff0a760d59c13c238f6bcdc32f8ce9cc62
- (NSString *) sha512:(NSString *) input withSalt: (NSString *) salt {
const char *cKey = [salt cStringUsingEncoding:NSUTF8StringEncoding];
const char *data = [input cStringUsingEncoding:NSUTF8StringEncoding];
unsigned char digest[CC_SHA512_DIGEST_LENGTH];
CCHmac(kCCHmacAlgSHA512, cKey, strlen(cKey), data, strlen(data), digest);
NSString *hash;
NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA512_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_SHA512_DIGEST_LENGTH; i++)
[output appendFormat:@"%02x", digest[i]];
hash = output;
return hash;
}
[self sha512:@"123" withSalt:@"123"];
Output: 3cafe40f92be6ac77d2792b4b267c2da11e3f3087b93bb19c6c5133786984b44
回答1:
Your code has two problems:
Your ObjC code appears to be calculating a SHA512 HMAC and your PHP code is calculating a SHA512 hash which are 2 different beasts. As far as I know [which is not far] the corresponding PHP code should be something like:
hash_hmac('SHA512', '123', '123' );
The output for the above is still much longer that the ObjC code, ie:
0634fd04380bbaf5069c8c46a74c7d21df7414888d980c27a16d5e262cb8c9059139c212d0926000faf026e483904cefae2f5e9d9bd5f51fbc2ac4c4de518115
Which is 128 characters [512 bits] long and ostensibly the expected length from SHA512 function.
回答2:
You are using HMAC on iOS, you need to use SHA and concatenate "123" and "123" the same as you are doing for php. HMAC does not just concatenate the key and data.
Use:
#import <CommonCrypto/CommonDigest.h>
extern unsigned char *CC_SHA512(const void *data, CC_LONG len, unsigned char *md)
回答3:
Edited the php code:
hash_hmac('SHA512', '123', '123' );
This solved the problem. Thanks!
来源:https://stackoverflow.com/questions/18859005/sha512-with-salt-for-ios