12

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.

Martin Thoma
  • 124,992
  • 159
  • 614
  • 958
John
  • 497
  • 2
  • 6
  • 20
  • 2
    Why did you accept an answer that doesn't answer the title of your question. Either change your accepted answer or change your question. If you want to know about os.random and its use then you should correct your accepted answer. – Charlie Parker Jul 03 '16 at 21:09

2 Answers2

21

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
jfs
  • 399,953
  • 195
  • 994
  • 1,670
Tim
  • 11,710
  • 4
  • 42
  • 43
8

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/

Community
  • 1
  • 1
Vladius
  • 4,268
  • 2
  • 20
  • 21
  • I am assuming that 16 is a argument to the built in function int that tells python that the given string is in base 16 (hexadecial). – Charlie Parker Jul 03 '16 at 21:05
  • Why did you give urandom 4 and not any other number? I know that 4 indicates a string of n random bytes suitable for cryptographic use, however, I keep seeing examples on the web where 4 is the the chosen number instead of say, 32 or 64. Why didn't you choose 64 say? More numbers more randomness/harder to predict, right? – Charlie Parker Jul 03 '16 at 21:07
  • Do you might explaining some of the details of your code? I have written above the details I could find out by reading the docs but wanted to know if there are any caveats (and how to fix them) or some important comments to give the readers when trying to re-use your code to optimize randomness and/or security. Thanks. – Charlie Parker Jul 03 '16 at 21:08
  • 10
    in python3, you need to use `rand=int.from_bytes(os.urandom(4), sys.byteorder)` – eafit Jul 30 '16 at 20:30