Nelson M
Nelson M

Reputation: 1718

OverflowError: cannot fit 'int' into an index-sized integer

In order to ensure that passwords are always stored, hashed and salted in the database, I decided to use a descriptor which will automatically hash the password when one is provided, e.g user.password = "jinja125".

Here is my code

from random import SystemRandom
from backports.pbkdf2 import pbkdf2_hmac, compare_digest

# ...snip...    

@password.setter
def password(self, value):
    # When a user is first created, give them a salt
    if self._salt is None:
        self._salt = bytes(SystemRandom().getrandbits(128))
    self._password = self._hash_password(value)

However when I try to run some tests, I get this error.

File "C:\Users\User\flask-python\site-tracker\app\users\models.py", line 34, in password
    self._salt = bytes(random.SystemRandom().getrandbits(simple_bit_counts))
OverflowError: cannot fit 'int' into an index-sized integer

How can I best fix this error?

Upvotes: 5

Views: 9631

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140168

From the documentation:

random.getrandbits(k) Returns a python long int with k random bits.

Here k==128 so 1<<128

check the size value you're trying to create a bytes array from (for instance):

>>> random.SystemRandom().getrandbits(128)
135192632488754159854542557748438253357

That's way too big for array indexing, not to mention the memory. You may want to reduce drastically your value. I suppose you meant 2**7 (7-bit random) not 1<<128

now if you wanted to generate 128 random bytes, you'd do that instead:

>>> bytes(random.randrange(0,255) for _ in range(128))
b'\xc9\x8fC\t\xe0\xc8\x8a5\xe4\xafb\xb5c.\x91\xea\x9aqUL\x11\x8d\xe4\xe3W\x87\xecM\xf8K\xa8\xf8\xbb\xb5 \x14H\xda\x1d]L\x13[n*\x87W\xd8\x90v\xfd\x8cQ\xdcY\xe4^\x95h8\xdc\'\x8e\xcb:\xea\xfbF\xf1zh8\xf63\x18WeV\xc6)\xce\xf9*w>\x83e\x0b#"\xf2\x97\xcf\xc2!\xddj\xb2\xbePl\xa2\r\xa7T\x8f\x14\x13\xa4\x1c\xeax\xacMJ2\x88A,\x11\xdev\xe1\xf8\x9b\x12\xd9c'

no need to call getrandbits for that. As Amadan noted, maybe you want 128 bits, not bytes, so make that range(16) instead. Well, now that you know, you can adjust to your actual needs.

Upvotes: 5

Related Questions