Reputation: 173
Here a snippet for generating password code, I have 2 questions about this, Could you please share how to understand?
urandom(6)
, help from urandom said,return n random bytes suitable for cryptographic use, it is say, it will return 6 bytes, is it 6 of ASCII ?
ord(c)
, get the decimal base for above bytes, why here transfer to decimal base?
Help for urandom
:
def urandom(n): # real signature unknown; restored from __doc__
"""
urandom(n) -> str
Return n random bytes suitable for cryptographic use.
"""
return ""
Python script:
from os import urandom
letters = "ABCDEFGHJKLMNPRSTUVWXYZ"
password = "".join(letters[ord(c) % len(letters)] for c in urandom(6))
Upvotes: 2
Views: 111
Reputation: 1850
ord()
function takes in a string containing a single character, and returns its Unicode index.
ex.
ord("A") => 65
ord("£") => 163
It is not used to get the decimal base of a byte as you mentioned, but rather its Unicode Index (its place in the Unicode Table).
P.S. :- Even though it returns the Unicode index but that doesn't mean its, range = len(Unicode Table) , the reason being that your python compiler may not support such long character sets under normal circumstances.
Upvotes: 1
Reputation: 59164
urandom
will return a byte (i.e. a value between 0 and 255). The sample code uses that value and the modulo operator (%
) to convert it into a value between 0 and 22, so that it can return one of the 23 letters (I
, O
, and Q
are excluded not to be confused with numbers).
Note that it is not a perfectly balanced algorithm as it would favour the first 3 letters (A
, B
, and C
) more, because 256 is not divisible by 23 and 256 % 23
is 3
.
Upvotes: 5