4

I need to generate several random strings for later use of length 128 bit (or 16 bytes, 32 hex characters). I have used this until now:

hex(random.getrandbits(128))[2:]

Unfortunately it turns out that it does not consistently produce 32 hex characters which is a requirement of my implementation. Some strings it produces are shorter than others, i.e. 30 or 31 characters, which is a problem.

Is there another way to achieve this?

1
  • When they're shorter, that just means the first bits came out all 0s. You could pad it back to the target length without modifying the distribution. Commented Apr 6, 2024 at 16:21

2 Answers 2

3
>>> import os
>>> os.urandom(16)
'S\x0e\xac\x91m\xcf\xf1\xae\x9b5\xf9A\xf3\xa2\xf9@'
Sign up to request clarification or add additional context in comments.

Comments

1

This approach should consistently produce a printable 32 character hex string from a pseudorandom 128 bit integer. It left pads with zeros, of course. Moreover, I believe this to be the simplest way to do it.

> import random

> randint = random.getrandbits(128)
> randstr = f'{randint:032x}'
> print(randstr)
00424c4bcbd1c00e3f4dd2bc52b2776b

Here is the code to test the output length:

import random

for i in range(1_000_000):
    randint = random.getrandbits(128)
    randstr = f'{randint:032x}'
    assert isinstance(randstr, str)
    assert (randint == int(randstr, 16)), (randint, randstr)
    assert (len(randstr) == 32), (randstr, len(randstr))
    assert (randstr == randstr.strip()), repr(randstr)
    print(randstr)

1 Comment

@Turing101 The answer has been rewritten and simplified to avoid the unnecessary use of encode and decode both.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.