python / cpython

The Python programming language
https://www.python.org
Other
63.38k stars 30.35k forks source link

Nicer interface to convert hashlib digests to int #72112

Open stevendaprano opened 8 years ago

stevendaprano commented 8 years ago
BPO 27925
Nosy @rhettinger, @stevendaprano, @bitdancer, @serhiy-storchaka

Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.

Show more details

GitHub fields: ```python assignee = None closed_at = None created_at = labels = ['type-feature'] title = 'Nicer interface to convert hashlib digests to int' updated_at = user = 'https://github.com/stevendaprano' ``` bugs.python.org fields: ```python activity = actor = 'serhiy.storchaka' assignee = 'none' closed = False closed_date = None closer = None components = [] creation = creator = 'steven.daprano' dependencies = [] files = [] hgrepos = [] issue_num = 27925 keywords = [] message_count = 4.0 messages = ['274102', '274141', '274147', '274173'] nosy_count = 4.0 nosy_names = ['rhettinger', 'steven.daprano', 'r.david.murray', 'serhiy.storchaka'] pr_nums = [] priority = 'normal' resolution = None stage = 'needs patch' status = 'open' superseder = None type = 'enhancement' url = 'https://bugs.python.org/issue27925' versions = [] ```

stevendaprano commented 8 years ago

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.

bitdancer commented 8 years ago

+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.

rhettinger commented 8 years ago

"int(x)" looks nice to me as well.

serhiy-storchaka commented 8 years ago

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.