“sample larger than population” in random.sample python

前端 未结 3 1989
隐瞒了意图╮
隐瞒了意图╮ 2020-12-16 00:31

creating a simple pass generator for myself, i noticed that if i want my population to be digits only (0-9) which is overall 10 options, if i want my length over 10, it wont

3条回答
  •  借酒劲吻你
    2020-12-16 00:55

    @Martijn Pieters is right. But since they state at https://docs.python.org/3.4/library/random.html:

    Warning: The pseudo-random generators of this module should not be used for security purposes. Use os.urandom() or SystemRandom if you require a cryptographically secure pseudo-random number generator.

    and the purpose of this is for generating passwords, I suggest this approach:

    import string
    import random
    
    set = string.letters + string.digits + string.punctuation
    length = 20
    
    password = ''.join( [ random.SystemRandom().choice( set) for _ in range( length) ] )
    
    print( password)
    

    Could anybody please confirm that this is more secure?

提交回复
热议问题