PHP for python package ('H')

I am rewriting an authentication library written in PHP in Python. This is all outdated code; the original developers have long passed. They used the PHP 'pack' command to convert the string to hex using the "H" flag. The PHP documentation describes this as "Hex string, high nibble first". I read another question (the Python equivalent of the php package ) that suggested using binascii.unhexlify (), but that complains whenever I pass a non-hexadecimal character.

So my question is what does the PHP pack function do with characters without hexadecimal characters? Throws them away, or there is an additional step that performs the translation. Is there a better way in Python than binascii.unhexlify?

So the package 'H *'

php -r 'print pack("H*", md5("Dummy String"));' 

Returns

 ??????=?PW?? 

In python:

 secret = binascii.unhexlify( "Dummy String" ) TypeError: Non-hexadecimal digit found 

Thanks for the help.

[EDIT]

So DJV was fundamentally right. At first I needed to convert the value to md5, however this is interesting. In python, the md5 library returns binary data using the digest method.

In my case, I could skip all binascii calls and just use

 md5.md5('Dummy String').digest() 

What is the same in PHP like:

pack ("H *", md5 ("Dummy String"));

Funny stuff. Good to know.

+4
source share
1 answer

I think you need it the other way around. "Dummy String" not a valid hex number. You can hexlify it:

 >>> binascii.hexlify('Dummy String') '44756d6d7920537472696e67' 

but not unhexlify . unhexlify takes a string in hex and turns it into this ASCII representation:

 >>> binascii.unhexlify('44756d6d7920537472696e67') 'Dummy String' 

You need an md5 string ( "Dummy String" in our case) and unhexlify it hash:

 import binascii import hashlib the_hash = hashlib.md5('Dummy String').hexdigest() print the_hash the_unhex = binascii.unhexlify(the_hash) print the_unhex 

What gives the hash, and the non-excluded hash:

 ec041da9f891c09b3d1617ba5057b3f5 L-?=¦PW 

Note: although the output does not look exactly the same as yours, “?????? =? PW ??”, “PW” and “=” in both cases make me pretty sure it is correct.

Learn more about hashlib and binascii

+3
source

Source: https://habr.com/ru/post/1469000/


All Articles