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?

- 200
- 1
- 13
1 Answers
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()
:
os.urandom(32)
returns 32 bytes of random databinascii.hexlify
returns the hex represntation of the bytes- as the return from
hexlify
is bytes we need todecode
it to get string
So as the original random bytes are being retrieved from os.urandom
this should be (cryptographically) secure randomness.

- 39,294
- 7
- 70
- 76
-
Okay so if i need to change its content after some time using same statement, will it still generate a unique key – Gagan Singh Nov 26 '19 at 11:04
-
@GaganSingh Yes. – heemayl Nov 26 '19 at 12:24
-
i know about accepting, sorry for being late and thanks for explanation – Gagan Singh Nov 26 '19 at 13:25