I need to convert this PHP function into Python but I don't even know, what is space padded binary string.
pack('A*', $string);
Python has struct.pack what should be probably used but I end here. Can somebody help and explain me the behaviour?
Thanks!
UPDATE:
This is the whole code I need to implement in Python. Until now I never heard about pack() so I am trying to understand what it exactly does so I can do it in Python:
function getSIGN($PID, $ID, $DESC, $PRICE, $URL, $EMAIL, $PWD) {
$bHash = pack('A*', $PID . $I开发者_运维百科D . $DESC . $PRICE . $URL . $EMAIL);
$bPWD = pack('A*', $PWD);
$SIGN = strtoupper(hash_hmac('sha256', $bHash, $bPWD, false));
return $SIGN;
}
I think that is a noop.
$string = 'asdf';
print pack('A10', $string) . "|<-\n";
would give you
asdf |<-
Since the *
means "take as many as possible," there is never any reason to pad.
IMHO you can just throw away the whole line.
Re. your Update:
The pack
function still serves no purpose, except for maybe implicitely converting all non-string arguments to strings.
Here is how you would do it in Python. I took the liberty to change the order of the parameters, so I can use parameter packing (which is not at all like string packing ;).
import hmac, hashlib
def get_sign(key, *data):
msg = ''.join(str(item) for item in data)
h = hmac.new(key, msg, hashlib.sha256)
return h.hexdigest().upper()
PHP:
$ print getSIGN(1234, 456, "foo", '123.45', 'http://example.com', 'foo@example.com', 'blah');
7FA608240FA2DC04F15DB2CDB58C83F4ED6C28C5C5B4063C5A7605F9D69F170B
Python:
In [12]: get_sign('blah', 1234, 456, "foo", '123.45',
'http://example.com', 'foo@example.com')
Out[12]: '7FA608240FA2DC04F15DB2CDB58C83F4ED6C28C5C5B4063C5A7605F9D69F170B'
精彩评论