2

Why do these (otherwise identical I think) snippets in php and python return different results?

python:

import base64
import hmac
from hashlib import sha1

access_key = 'AKIAIOSFODNN7EXAMPLE'.encode("UTF-8")
secret_key = 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY'.encode("UTF-8")

string_to_sign = 'GET\n\n\nTue, 27 Mar 2007 19:36:42 +0000\n/awsexamplebucket1/photos/puppy.jpg'.encode("UTF-8")

signature = base64.encodebytes(
                                hmac.new(
                                         secret_key, string_to_sign, sha1
                                         ).digest()
                                ).strip()

print(f"{access_key.decode()}:{signature.decode()}")

returns AKIAIOSFODNN7EXAMPLE:qgk2+6Sv9/oM7G3qLEjTH1a1l1g=

php:

$access_key = 'AKIAIOSFODNN7EXAMPLE';
$secret_key = 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY';

$string_to_sign = 'GET\n\n\nTue, 27 Mar 2007 19:36:42 +0000\n/awsexamplebucket1/photos/puppy.jpg';

echo $access_key . ':' . base64_encode( hash_hmac('sha1', $string_to_sign, $secret_key, true) );

returns AKIAIOSFODNN7EXAMPLE:V2JAq4zUc51YplB6g2Yo23Z0Hbk=

both files are utf-8 encoded

kombi
  • 29
  • 3

1 Answers1

1

I don't know anything about Python, but in PHP there's a difference between '\n' and "\n". The first is just the two characters, the second is a single newline character. Perhaps that could explain it? You could try the double quotes.

Yes, from what I read in the Python documentation it doesn't distinguish between ' and ", and therefore will see '\n' as a single newline character.

I tried:

<?php

$access_key = 'AKIAIOSFODNN7EXAMPLE';
$secret_key = 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY';

$string_to_sign = "GET\n\n\nTue, 27 Mar 2007 19:36:42 +0000\n/awsexamplebucket1/photos/puppy.jpg";

echo $access_key . ':' . base64_encode( hash_hmac('sha1', $string_to_sign, $secret_key, true) );

and it does return the same as in Python. See: https://3v4l.org/1Hp7W

KIKO Software
  • 15,283
  • 3
  • 18
  • 33
  • ..and that was precisely it! In the end I tried with access_key 'foo' and secret_key 'bar' and it nicely returned the same in php and python. I can't believe I spent so much time overlooking that I was using single quotes, thanks KIKO! – kombi Apr 15 '23 at 05:57