Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Python random.randbytes() Function



The Python random.randbytes() function in Python is used to generate n random bytes. This function is part of the random module, which provides various functions to generate random numbers and sequences. The primary use of this function is to create random byte sequences, which can be useful in various applications such as testing, simulations, or any scenario where random binary data is required.

However, it is important to note that this fuction should not be used for generating security tokens or cryptographic keys, as it does not guarantee cryptographic security. For such purposes, you can use the secrets.token_bytes().

This function is not accessible directly, so we need to import the random module and then we need to call this function using random static object.

Syntax

Following is the syntax of the Python random.randbytes() function −

random.randbytes(n)

Parameters

This function accepts the following parameter −

  • n − Size of the bytes to be generated.

Return Value

This function returns a randomly generated sequence of bytes of the specified size.

Example 1

Let's look at an example of how to use the Python random.randbytes() function to generate 8 random bytes.

import random

random_bytes = random.randbytes(8)

print(random_bytes)

When we run the above program, it produces the following result −

b'\xc7\xf8E\x8a\xa4\xb7\xa4\x90'

Example 2

This example generate a random hexadecimal number, here we are using the random.randbytes() function to create a sequence of random bytes and then convert them to a hexadecimal string.

import random

# Generate 8 random bytes
random_bytes = random.randbytes(8)

# Convert bytes to hexadecimal string
random_hex = random_bytes.hex()

print(random_hex)

The output of the above code is as follows −

08f3000d23c7f2be

Example 3

Here is another example uses the random.randbytes() function to generate the random bytes, then convert the generated random bytes into hexadecimal string using the bytes.hex() function and finally, swaps the case of the hexadecimal string.

import random

# Generate 2 random bytes
random_bytes = random.randbytes(2) 
print("2 random Bytes",random_bytes)

# Convert bytes to hexadecimal string
random_hex = random_bytes.hex()
print("Hexadecimal string",random_hex)

# Swap the case of hexadecimal string
result = random_hex.swapcase()
print("Output hexadecimal string", result)

Following is an output of the above code −

2 random Bytes b'\xa6\xc0'
Hexadecimal string a6c0
Output hexadecimal string A6C0
python_modules.htm
Advertisements