Hello
need your help in a simple issue:
I want to create a random 16 chars message from this (0123456789ABCDEF)
so the output will be like this:
"AAB1C70ADD84C701"
I mange only to create a random int
new_data = random.randint(111111111111,999999999999)
but how do I add Hex values?
Thanks ,
Here's one option:
from random import randint
chars = '0123456789ABCDEF'
hex_array = [chars [randint (0, 15)] for x in range (16)]
hex_string = ''.join (hex_array)
print (hex_string)
>>> import random
>>> f"{random.randint(0,2**(4*16)):016X}"
'47A30C8F1A3627C7'
Picks a random number between 0 and 0xFFFFFFFFFFFFFFFF, then prints that number out as as 16 digit hex string.
You could also use the
uuid
module, since uuids are random and hex strings.
import uuid
rand_id = uuid.uuid4()
as_hex = rand_id.hex
value = as_hex[:16]
print(value)
#=> 00fcabb895d144d3
But the best is probably to be explicit about what you're doing...
import random
import string
# 0-9, a-f, A-F
chars = string.hexdigits
# remove a-f
chars = list(set(chars.upper()))
message = ''.join(random.choice(chars) for _ in range(16))
print(message)
#=> 671A097FE9A211FB
Similar to bowlofred solution:
import random
def get_random_hex_str(hex_length):
if hex_length % 2 != 0:
raise ValueError("hex_length must be even")
maximum = 2 ** (4 * hex_length) - 1
value = random.randint(0, maximum)
return f"{value:0{hex_length}x}"
A cryptographic safe solution is the use of
os.urandom
import os
from binascii import hexlify
def get_random_hex_str(hex_length):
if hex_length % 2 != 0:
raise ValueError("hex_length must be even")
return hexlify(os.urandom(hex_length // 2)).decode()
Thank you all for the help !
so many options to choose from
Thanks ,