Python os.urandom() method: example, convert to string

OS module in Python provides functions for interacting with the operating system. The os.urandom(size) is a method often used when it comes to encryption. It is used as a cryptographically secure pseudo-random number generator.

This method returns random bytes from an OS-specific randomness source, which are unpredictable enough for cryptographic applications. However, its quality depends on the OS.

os.urandom() example

import os

key = os.urandom(32)
print(key)
#output: b'\x9a\x1a|\n\x14G\x1c\xd8\x87\xc9&\xd50\xc4\x1d\x9a1y\xe5\x8cg\xe2\xde$\xce\xc5/\x8d\xc0S\x8e\xd0'

Convert urandom() data to a string

We can use base64 to convert os.urandom()’s bytes result to a string.

import os
from base64 import b64encode

key = os.urandom(64)
print(key)
#output: b'\xc7N\x98\xa2w\xd8L-H&\x98\xfd\xcf\xa6\x12]F\xf6\x87\xe3%t\xa6\xf8\x91E\xb2\xce\xf0\x0fg\x111\x05\x0f!\xc3S\x99\xd1At\x10\xd1\xcf6\xf0z\xc8Y\xfca\xdf\xa8\xee\xf9\xbbB\xb9\x91%\x8e\x08&'
text = b64encode(key).decode('utf-8')
print(text)
#output: x06YonfYTC1IJpj9z6YSXUb2h+MldKb4kUWyzvAPZxExBQ8hw1OZ0UF0ENHPNvB6yFn8Yd+o7vm7QrmRJY4IJg==

Use urandom() in encryption

We can combine this method to generate keys for encryption method.

key = os.urandom(32)
iv = os.urandom(16)
cipher = Cipher(algorithms.AES(key), modes.CBC(iv))

You can read about the top encryption libraries for Python on another post.

Leave a Comment

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close