简体   繁体   中英

Python pack to PHP pack

I am trying convert a Python script to PHP. However I am having trouble getting the format right.

Python:

print(hashlib.sha1(struct.pack('L', 1)).hexdigest()) 

Output:

3da89ee273be13437e7ecf760f3fbd4dc0e8d1fe

PHP:

echo sha1(pack('L', 1));

Output:

3c585604e87f855973731fea83e21fab9392d2fc

Can someone please point me in right direction to get the same output in both languages?

The differences occurs because of different integer sizes. While L in the php version of pack() uses hardcoded 32bit integers, Python by default uses the machine integer size. If you are working on a 64bit system you'll notice the difference. (As shown in the question)

You need to use the = in python to standardize the aligment and the size:

print(hashlib.sha1(struct.pack('=L', 1)).hexdigest())

Output:

3c585604e87f855973731fea83e21fab9392d2fc

Please refer to this docs:

This appears to be a 32 vs 64-bit issue. Are you running a 64-bit version of Python?

Note that according to the Python docs , L is an "unsigned long". Since you're not specifying a byte order, size and alignment character, Python will default to native . On Linux, that means 8 bytes on 64-bit, and 4 bytes on 32-bit.

It's always best to tell Python exactly what you mean when working with binary data:

  • < for little-endian, standard size, or
  • > for big-endian, standard size.

This will eliminate any differences, depending on what type of machine you're running on.

This example shows that you're probably using a 64-bit build of python, as L == Q (64-bit).

>>> print(hashlib.sha1(struct.pack('<I', 1)).hexdigest())
3c585604e87f855973731fea83e21fab9392d2fc

>>> print(hashlib.sha1(struct.pack('<Q', 1)).hexdigest())
3da89ee273be13437e7ecf760f3fbd4dc0e8d1fe

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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