NumPy: How to Generate Random Bytes (4 Examples)

Updated: March 2, 2024 By: Guest Contributor Post a comment

NumPy, a fundamental package for scientific computing with Python, offers an extensive range of options for generating random data. Among these options is the ability to generate random bytes, which can be useful for a variety of applications such as cryptography, simulations, or testing. In this tutorial, we’ll explore how to generate random bytes using NumPy, covering four examples that range from basic to more advanced techniques.

Getting Started

Before we dive into the examples, let’s ensure that NumPy is installed in our environment. You can install NumPy using pip:

pip install numpy

Once installed, you can import NumPy in your Python script:

import numpy as np

Example 1: Generate a Single Set of Random Bytes

The simplest way to generate random bytes is by using the np.random.bytes function. This function requires the number of random bytes you wish to generate as its parameter.

import numpy as np  

random_bytes = np.random.bytes(4) 
print(random_bytes)

Output might look like something this, though the specific bytes will differ each time you run it:

b'\x93\xad\x85\xe2'

This example generates 4 random bytes, which can be useful for generating keys, salt values, or any situation where a small, fixed amount of randomness is required.

Example 2: Generating Random Bytes for Cryptographic Use

While numpy’s random bytes can be utilized for testing or simulations, it’s important to note that they might not be secure for cryptographic purposes. Python’s secrets module should be used for generating cryptographic random bytes. However, for educational purposes, let’s generate a significant amount of random bytes using NumPy, simulating a scenario whereby one requires a large volume of randomness:

import numpy as np  

crypto_bytes = np.random.bytes(1024) 
print(len(crypto_bytes))

The output will show that 1024 bytes have been generated, though the actual byte content will vary with each execution.

Example 3: Creating Random Byte Arrays

Moving beyond a single batch of random bytes, you can use NumPy’s array operation capabilities to generate arrays of random bytes. This example demonstrates how to create a 2D array filled with random bytes, with each byte generated independently.

import numpy as np  

shape = (4, 4) 
array_of_bytes = np.zeros(shape, dtype='|S1') 

for i in range(shape[0]): 
    for j in range(shape[1]): 
        array_of_bytes[i][j] = np.random.bytes(1) 

print(array_of_bytes)

Output (vary):

[[b'7' b'\x87' b'\xc0' b'\x01']
 [b'L' b'\xfe' b',' b'\x12']
 [b'\xb8' b',' b'G' b'!']
 [b'\xf5' b'6' b'\xd6' b'"']]

Here we create a 4×4 array of zeros with a string data type capable of storing a single byte. Then, we fill this array with random bytes. The output will showcase a 4×4 matrix where each element is a random byte.

Example 4: Generating Random Bytes Using Seed for Reproducibility

Reproducibility is an essential aspect of scientific computation. NumPy allows for the replication of random byte sequences by setting a seed. This can be particularly useful in testing or simulations where consistent results are crucial.

import numpy as np  

np.random.seed(42) 
seeded_bytes = np.random.bytes(8) 
print(seeded_bytes)

When using a seed, the output will be the same each time the code is run. For the seed value of 42, the output will look something like this (though, it’s crucial to remember that different versions of NumPy may generate different outputs even with the same seed):

b'f\xdc\xe1_\xb3=\xea\xcb'

Conclusion

Generating random bytes in Python using NumPy is a straightforward process, whether you need a small amount for quick tasks or large volumes for simulation purposes. While NumPy provides an effortless way to generate these bytes, remember that for cryptographic needs, the standard library’s secrets module is the go-to choice. The examples provided in this guide illustrate just a few ways NumPy can be used to generate random bytes for various applications. Experiment with these techniques as a foundation for integrating randomness into your Python projects.