This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Nicer interface to convert hashlib digests to int
Type: enhancement Stage: needs patch
Components: Versions:
process
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: r.david.murray, rhettinger, serhiy.storchaka, steven.daprano
Priority: normal Keywords:

Created on 2016-09-01 08:31 by steven.daprano, last changed 2022-04-11 14:58 by admin.

Messages (4)
msg274102 - (view) Author: Steven D'Aprano (steven.daprano) * (Python committer) Date: 2016-09-01 08:31
hashlib digests should have a nicer interface to allow conversion to ints.

Currently we write int(x.hexdigest(), 16) which is less than obvious and easy to get wrong. It would be nice to be able to just say int(x) (that's my strong preference) or x.as_int().

Use-case: sometimes we need to store hashes in a database table which, for historical reasons, is an integer.
msg274141 - (view) Author: R. David Murray (r.david.murray) * (Python committer) Date: 2016-09-01 15:32
+1  I just wanted this recently.  Also note that going through hexdigest/int isn't particularly efficient, so an object-supported fast way to do this would be nice.
msg274147 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2016-09-01 15:50
"int(x)" looks nice to me as well.
msg274173 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) Date: 2016-09-01 19:41
There is another way:

    int.from_bytes(x.digest(), 'big')

Note that converting to int you lose the length of the digest. md5 digest d41d8cd98f00b204e9800998ecf8427e and sha1 digest 00000000d41d8cd98f00b204e9800998ecf8427e are converted to the same int. This can add a vulnerability.
History
Date User Action Args
2022-04-11 14:58:35adminsetgithub: 72112
2016-09-01 19:41:46serhiy.storchakasetnosy: + serhiy.storchaka
messages: + msg274173
2016-09-01 15:50:56rhettingersetnosy: + rhettinger
messages: + msg274147
2016-09-01 15:32:10r.david.murraysetnosy: + r.david.murray

messages: + msg274141
stage: needs patch
2016-09-01 08:31:48steven.dapranocreate