Trying to digitally sign via HMAC-SHA1 with PHP
Asked Answered
I

3

9

I'm trying to setup some Google Maps Premier API action, and to do so, I need to sign my URLs to authenticate. If you go down to Signature examples, there is some Python, C# and Java code to show you how to do the signature via HMAC-SHA1. There is also an example so that I can to test my PHP implementation. However, I just can't seem to get it to work.

Here's my code:

$key = "vNIXE0xscrmjlyV-12Nj_BvUPaw=";

$data = "/maps/api/geocode/json?address=New+York&sensor=false&client=clientID";

$my_sign = hash_hmac("sha1", $data, base64_decode($key));
$my_sign = base64_encode($my_sign);

$valid_sign = "KrU1TzVQM7Ur0i8i7K3huiw3MsA=";

When, I run this, I get a signature of:

ZDRlNGMwZjIyMTA1MWM1Zjk0Nzc4M2NkYjlmNDQzNDBkYzk4NDI4Zg==

Which totally doesn't match.

Things I have thought about:

  1. The key is in Modified URL encoded format, so changing - and _ to + and / also doesn't work
  2. The Python example code does indeed work, so this is a valid example.
  3. Completely rewriting our code-base in python instead of PHP (I inherited it).
Intonate answered 26/6, 2010 at 20:30 Comment(0)
M
21

You have 2 problems at least,

  1. The Google uses special URL-safe Base64. Normal base64_decode doesn't work.
  2. You need to generate the SHA1 in binary.

Try this,

$key = "vNIXE0xscrmjlyV-12Nj_BvUPaw=";
$data = "/maps/api/geocode/json?address=New+York&sensor=false&client=clientID";
$my_sign = hash_hmac("sha1", $data, base64_decode(strtr($key, '-_', '+/')), true);
$my_sign = strtr(base64_encode($my_sign), '+/', '-_');
Merrifield answered 27/6, 2010 at 0:42 Comment(3)
Your code worked. I swear that I tried to switch those two characters around manually and still couldn't see the correct result. Perhaps that was not correct though. In any case, thanks for your help! :)Intonate
@ZZCoder Your example was useful still today - thanks for writing it; signing Amazon S3 bucket requests is very similar. $signature = rawurlencode(base64_encode(hash_hmac("sha1", $stringToSign, $secret_access_key, true)));Viceregent
Geek Stocks suggestion for S3 uploads works when not using the rawurlencode function. This upload solution has good S3/PHP info that can be used without ever using their library: plupload.com/docs/v2/Upload-to-Amazon-S3Galcha
D
3

A php example is available at http://gmaps-samples.googlecode.com/svn/trunk/urlsigning/UrlSigner.php-source

Ditter answered 26/4, 2012 at 6:43 Comment(0)
F
0

I assume your trying to sign the url for OAuth?

Try out this library: http://code.google.com/p/oauth/

Footlambert answered 26/6, 2010 at 21:9 Comment(1)
Could also be signing for Google static maps or so.Salas

© 2022 - 2024 — McMap. All rights reserved.