API · Python

Python os.urandom() Function

Python’s os.urandom() function returns random bytes from an operating-system source for cryptographic use.

On this page

Python’s os.urandom() function returns bytes from an operating-system randomness source. Use it when an application needs random bytes suitable for cryptographic purposes, such as key material; do not treat its output as a printable string or promise that separate calls will be unique.

Syntax and Parameters

Call the function with an integer specifying how many bytes to request: os.urandom(size). The argument is a byte count, not a string length or a range of character values. Import os before calling it. For example, a request for 16 bytes produces a bytes value whose length is 16.

Return Value and Security

The return value is a bytes object. Its contents can include any byte value, including values that do not correspond to printable characters. The operating system provides the randomness source, and Python documents this function for cryptographic use. Random output is not guaranteed to be unique: collisions are possible, so do not use a generated value as a uniqueness check or assume that repeating a request produces a different value.

Choose the requested byte count for the application’s security needs and the format expected by the code that consumes it. Keep the value as bytes when the next operation accepts bytes. If a protocol or storage format needs text, encode the bytes explicitly rather than decoding arbitrary random bytes as though they were ordinary text.

Use os.urandom() to Generate Random Bytes

Run this example to request 16 bytes and inspect their length:

import os

random_bytes = os.urandom(16)
print(len(random_bytes))

The length check lets you confirm the requested byte count; the random byte contents vary between calls.

Convert Random Bytes to Text

Base64 is one option when bytes need a printable representation. The encoded value is text representing the original bytes; it is not the same value or type as those bytes. Decoding the Base64 value restores the original byte sequence.

import os
from base64 import b64encode, b64decode

random_bytes = os.urandom(10)
encoded_text = b64encode(random_bytes).decode("ascii")
restored_bytes = b64decode(encoded_text)
print(len(random_bytes), restored_bytes == random_bytes)

This example demonstrates the conversion and round trip without displaying a particular random result. Base64 is an encoding, not encryption, and it does not make secret data safe to disclose.

Handle Randomness Source Errors

A randomness source may be unavailable or fail in a particular runtime environment. Do not assume a specific exception name or operating-system cause without checking the documentation for the Python version and platforms your application supports. Follow that documented behavior in your error handling, and avoid silently substituting a different source with different security properties. If the application cannot safely continue without cryptographic randomness, make the failure visible to its caller rather than proceeding with predictable data.

How os.urandom() Differs from random

The random module is intended for general-purpose pseudorandom values, such as simulations and games. Its generator is designed for reproducible sequences when seeded, which is useful in those settings but unsuitable for secrets. os.urandom() requests bytes from the operating-system randomness source for cryptographic purposes. Choose the API based on the task: use random for ordinary randomized behavior and os.urandom() when cryptographically suitable random bytes are needed. Their output types and purposes differ, so a timing comparison between them would not establish which one is appropriate for a security-sensitive task.