Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

review random generator #7

Open
clach04 opened this issue Jan 29, 2023 · 0 comments
Open

review random generator #7

clach04 opened this issue Jan 29, 2023 · 0 comments

Comments

@clach04
Copy link
Owner

clach04 commented Jan 29, 2023

  • Py 3.6 >= https://docs.python.org/3/library/secrets.html#module-secrets - secrets.token_bytes()

  • https://www.pycryptodome.org/src/random/random#Crypto.Random.get_random_bytes

  • see other personal code that uses alternative system random (os.urandom)

    try:
        from secrets import choice, randbelow  # Python 3.6 module
    except ImportError:
        import random as _py_random
        random = _py_random  # backup(, backup) plan
    
    # Potentially overkill, use system random numbers
    # Nested exception catching for older Python version
    try:
        try:
            random = _py_random.SystemRandom()
        except NotImplementedError:
            # not available
            pass
    except AttributeError:
        # Pre Python 2.4
        pass
    
    def randbelow(x):
        return random.randint(0, x)
    choice = random.choice
    

For completeness, (Linux) should not be needed:

try:
    urandom = os.urandom
except AttributeError:
    if os.path.exists('/dev/urandom'):
        def urandom(n):
            # UNIX ONLY
            f = open('/dev/urandom')
            result = f.read(n)
            f.close()
            return result
    else:
        def urandom(n):
           s = []
           for i in xrange(n):
              r = random.randint(0,255)
              s.append(chr(r))
           return ''.join(s)

Windows only:

win32prng.getRandomBytes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant