I’m trying to convert some Ruby code into Python. I’m having troubles with this line:
Digest::MD5.digest(message).unpack('L*')
I think I should use the struct module and the hashlib one, but if I do:
struct.unpack('L', hashlib.md5(message).digest())
I get this error:
struct.error: unpack requires a bytes object of length 4
What should I do?
Thank you,
rubik
P.S. The output should be a list of 4 x 32 bit ints:
irb(main):039:0> Digest::MD5.digest('Hash').unpack('L*')
=> [631892218, 1967199614, 3683860954, 4130231798]
There is no support for arbitrary length unpacks (the
*operator). You’ll have to specify a repeater manually.Luckily the struct module does let you specify a fixed length, and the hashlib module tells you how many bytes to expect. By putting an integer number before the
Lyou specify the number of times to apply the pattern. And a specific hash in thehashliblibrary has a.digest_sizeattribute that tells you how many bytes long a specific hash is.To combine these:
If you don’t even want to hardcode the
4there, you can askstruct.calcsizefor the size of anLunsigned long as well:In fact, on 64 bit platforms like my Mac,
Lis 8 bytes, so the latter calculation matters enormously if you are deploying across different architectures.