Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3 os.urandom

Where can I find a complete tutorial or documentation on os.urandom? I need to get get a random int to choose a char from a string of 80 characters.

like image 573
John Avatar asked Nov 04 '12 07:11

John


People also ask

What is os urandom Python?

os. urandom() method is used to generate a string of size random bytes suitable for cryptographic use or we can say this method generates a string containing random characters. Syntax: os.urandom(size) Parameter: size: It is the size of string random bytes.

What does urandom do?

The /dev/urandom device provides a reliable source of random output, however the output will not be generated from an equal amount of random input if insufficient input is available. Reads from the /dev/urandom device always return the quantity of output requested without blocking.

Is Python a DIR os?

isdir() method in Python is used to check whether the specified path is an existing directory or not. This method follows symbolic link, that means if the specified path is a symbolic link pointing to a directory then the method will return True. Parameter: path: A path-like object representing a file system path.

What is os name in Python?

The os.name method in Python get the name of the underlying operating system (OS). This is a method of the OS module. The following are the operating systems that are currently registered. RISC OS. Portable Operating System Interface (POSIX)


2 Answers

If you just need a random integer, you can use random.randint(a, b) from the random module.

If you need it for crypto purposes, use random.SystemRandom().randint(a, b), which makes use of os.urandom().

Example

import random

r = random.SystemRandom()
s = "some string"
print(r.choice(s)) # print random character from the string
print(s[r.randrange(len(s))]) # same
like image 164
Tim Avatar answered Oct 20 '22 03:10

Tim


Might not exactly be on topic, but I want to help those coming here from a search engine. To convert os.urandom to an integer I'm using this:

 import os

 rand = int(int(str(os.urandom(4), encoding="UTF-8")).encode('hex'), 16)
 # You can then 'cycle' it against the length.
 rand_char = chars_list[rand % 80] # or maybe '% len(chars_list)'

Note: The range of the index here is up to that of a 4-byte integer. If you want more, change the 4 to a greater value.

The idea was taken from here: https://pythonadventures.wordpress.com/2013/10/04/generate-a-192-bit-random-number/

like image 27
Vladius Avatar answered Oct 20 '22 01:10

Vladius