Python Forum
How to create random hex message - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How to create random hex message (/thread-32168.html)



How to create random hex message - korenron - Jan-25-2021

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 ,


RE: How to create random hex message - korenron - Jan-25-2021

(Jan-25-2021, 03:18 PM)korenron Wrote: Hello
need your help in a simple issue:

I want to create a random 16 chars string 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 ,



RE: How to create random hex message - BashBedlam - Jan-25-2021

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)



RE: How to create random hex message - bowlofred - Jan-25-2021

>>> 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.


RE: How to create random hex message - nilamo - Jan-25-2021

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



RE: How to create random hex message - DeaD_EyE - Jan-26-2021

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()



RE: How to create random hex message - korenron - Jan-26-2021

Thank you all for the help !

so many options to choose from Smile

Thanks ,