Python Forum
How to create random hex message
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to create random hex message
#6
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()
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
How to create random hex message - by korenron - Jan-25-2021, 03:18 PM
RE: How to create random hex message - by korenron - Jan-25-2021, 03:34 PM
RE: How to create random hex message - by bowlofred - Jan-25-2021, 04:54 PM
RE: How to create random hex message - by nilamo - Jan-25-2021, 05:29 PM
RE: How to create random hex message - by DeaD_EyE - Jan-26-2021, 10:28 AM
RE: How to create random hex message - by korenron - Jan-26-2021, 10:42 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  [split] why can't i create a list of numbers (ints) with random.randrange() astral_travel 7 1,668 Oct-23-2022, 11:13 PM
Last Post: Pedroski55
  how to create my own custom logging message maiya 4 2,473 Jul-15-2020, 05:42 PM
Last Post: maiya
  Create random pairs Dennisp44 3 8,186 Jun-02-2018, 05:51 AM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020