简体   繁体   English

iOS base64编码返回的结果与php不同

[英]iOS base64 encoding returning different result than php

I'm building an iOS app making use of our own web service but am having some issues when base64 encoding data within iOS and trying to compare it with the same data encoded using PHP base64_encode() function. 我正在构建一个利用我们自己的Web服务的iOS应用,但是在iOS中对base64编码数据进行尝试并将其与使用PHP base64_encode()函数编码的相同数据进行比较时遇到了一些问题。

iOS side: iOS端:

/*
 * Generating a hash within an NSData object, which then I try to base64 encode
 *  making use of the Base64 library included with RestKit.
 */
const char *cKey  = [private_key cStringUsingEncoding:NSASCIIStringEncoding];
const char *cData = [password cStringUsingEncoding:NSASCIIStringEncoding];  
unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];   
CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);  
NSData *HMAC = [[NSData alloc] initWithBytes:cHMAC length:sizeof(cHMAC)];
NSString *myHash = [HMAC base64EncodedString];

PHP Side: PHP方面:

$hash = hash_hmac('sha256',$data,$key);
$encoded_hash = base64_encode($hash);

And the output looks like: 输出看起来像:

iOS HMAC: <3ae3bbed 508b62aa 9bd8e92e 357e1467 e888cd3d a1ad5aa2 7692db23 5415eb0d>
iOS myHash: OuO77VCLYqqb2OkuNX4UZ+iIzT2hrVqidpLbI1QV6w0=

PHP hash: 3ae3bbed508b62aa9bd8e92e357e1467e888cd3da1ad5aa27692db235415eb0d
PHP encoded_hash: M2FlM2JiZWQ1MDhiNjJhYTliZDhlOTJlMzU3ZTE0NjdlODg4Y2QzZGExYWQ1YWEyNzY5MmRiMjM1NDE1ZWIwZA==

As you can see, when comparing iOS' HMAC and PHP Hash they contain the same characters, but once you base64 encode this, the result is not the same. 如您所见,在比较iOS的HMAC和PHP哈希时,它们包含相同的字符,但是一旦对base64进行编码,结果将不相同。

Your iOS one is correct. 您的iOS是正确的。

The PHP one is the string 3ae3bbed508b62aa9bd8e92e357e1467e888cd3da1ad5aa27692db235415eb0d base-64 encoded. PHP一个是字符串 base 3编码的字符串 3ae3bbed508b62aa9bd8e92e357e1467e888cd3da1ad5aa27692db235415eb0d ie the bit stream being encoded here is those ASCII characters. 即,此处编码的位流是那些ASCII字符。 So the first 3 is 0x33 , the a is 0x61 , etc. So you're encoding 0x3361... actually. 因此,前30x33a0x610x3361... 。所以实际上是在编码0x3361... Does that make sense? 那有意义吗?

For the PHP you want: 对于您想要的PHP:

$hash = hash_hmac('sha256',$data,$key,true);
$encoded_hash = base64_encode($hash);

That tells hash_hmac to return the raw output rather than a hex string. 这告诉hash_hmac返回原始输出,而不是十六进制字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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