Cryptographically random numbers

Paul Rubin http
Tue Mar 7 15:12:56 EST 2006


Gervasio Bernal <gervasiobernal at speedy.com.ar> writes:
> How can I generate a random string containing digits, symbols and
> letters? I will use this random string for the key of a cryptographic
> algorithm.

Generally if this is a string that some human user has to type in,
it's preferable to select some words randomly from a dictionary rather
than use an easily-garbled string of symbols.  If the string will be
handled entirely by computers, just use a random string of bytes (like
os.urandom(20)) without worrying about whether they're printable
characters.  If you really want a random-looking string of specific
characters, a simple way is:

   usable_characters = string.letters + string.digits
   ...
   # generate one character from the set (repeat as needed)
   a,b = map(ord, os.urandom(2))
   c = (a*256 + b) % len(usable_characters)

Notice that the characters will have slightly unequal probability
(unless the usable character set's size is a power of 2), but the
effect on the output entry is insignificant.



More information about the Python-list mailing list