djangodjango-rest-frameworkauth-tokenbinascii

What does binascii.hexlify(os.urandom(32)).decode() mean?


I'm trying to develop a function which would refresh token model in django rest framework.They seem to use binascii.hexlify(os.urandom(32)).decode() for generating unique tokens for every user.How does this line ensures that token generated by it will always be unique.Suppose if i want to refresh content of token after every 10 months ,then, will binascii.hexlify(os.urandom(32)).decode() will generate unique key that has not been used by any current user or i need to check whether it is being used or not?


Solution

  • help(os.urandom) says:

    Return a bytes object containing random bytes suitable for cryptographic use.

    On Linux this will use the /dev/urandom character device which is designed to be cryptographically secure. Only time it could fail to generate so would be the very early stage of boot when the entropy pool is not initialized yet 1. But once it's initialized and seeded from the previouse seed, device drives and so on you would generate cryptographic grade randomness.

    Also check man 4 urandom.

    1 getrandom(2) system call is there for these cases, which is blocking unlike reading from /dev/urandom.


    binascii.hexlify(os.urandom(32)).decode():

    So as the original random bytes are being retrieved from os.urandom this should be (cryptographically) secure randomness.