Note that there are some explanatory texts on larger screens.

plurals
  1. POiOS - PHP Match UTF-8 encoding
    text
    copied!<p>I am playing around with signatures for request on the iPhone. I have a simple PHP script running that will verify incoming JSON data against the signature in the header (all in all it is very similar to two-legged OAuth).</p> <p>The following Obj-C code generates the signature:</p> <pre><code>const char *cKey = [kConsumerSecret cStringUsingEncoding:NSUTF8StringEncoding]; const char *cData = [payload cStringUsingEncoding:NSUTF8StringEncoding]; NSLog(@"Payload: %s", cData); 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 *signature = [hmac base64EncodedString]; </code></pre> <p>And the verifying PHP code looks like this:</p> <pre><code>$originalPayload = '{"name":"Ben’s iPhone"}'; // The message received from iOS $hash = hash_hmac("sha256", $originalPayload, "Secret Key", TRUE); $signature = strtr(base64_encode($hash), array('=' =&gt; '', '+' =&gt; '-', '/' =&gt; '_')); </code></pre> <p>The functions work perfectly fine when using ASCII characters. But when they contain UTF-8 characteres iOS calculates the signature based on:</p> <pre><code>Ben‚Äôs iPhone </code></pre> <p>While PHP calculates it based on:</p> <pre><code>Ben\u2019s iPhone </code></pre> <p>Making the signatures invalid. I have tried multiple approaches and none of them have yielded any results. Does anyone have an idea for how to solve this issue?</p> <p>Remark: Yes, I could simply use OAuth, but I'm just curious on how to implement it myself.</p> <p><strong>Update:</strong> I have tracked down the problem to a part in the code, that modifies the parsed JSON array in the PHP code. In order to hash, but not include it in the body, I added the temporary index 'time' that contained a UTC timestamp. That modification of the original array made PHP change the character representation (escaping UTF-8 characters). Just appending the timestamp work fine.</p> <p>Nonetheless the functions should yield the same result, shouldn't they?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload