High quality, simple random password generator

前端 未结 27 2470
渐次进展
渐次进展 2020-12-22 17:06

I\'m interested in creating a very simple, high (cryptographic) quality random password generator. Is there a better way to do this?

import os, random, strin         


        
27条回答
  •  天涯浪人
    2020-12-22 17:07

    You can't trust python's pseudo random number generator when generating a password. It is not necessarily cryptographically random. You are seeding the pseudo random number generator from os.urandom which is a good start. But then you depend on python's generator after that.

    A better choice would be the random.SystemRandom() class which takes random numbers from the same source as urandom. According to the python documentation that should be good enough for cryptographic use. The SystemRandom class gives you everything that the main random class does but you don't need to worry about the pseudorandomness.

    Example code using random.SystemRandom (for Python 3):

    import random, string
    length = 13
    chars = string.ascii_letters + string.digits + '!@#$%^&*()'
    
    rnd = random.SystemRandom()
    print(''.join(rnd.choice(chars) for i in range(length)))
    

    Note: Your mileage may vary - the Python Documentation says that random.SystemRandom availability varies by operating system.

提交回复
热议问题