Random string generation with upper case letters and digits

前端 未结 30 3573
逝去的感伤
逝去的感伤 2020-11-22 02:51

I want to generate a string of size N.

It should be made up of numbers and uppercase English letters such as:

  • 6U1S75
  • 4Z4UKK
  • U911K4
30条回答
  •  轮回少年
    2020-11-22 03:01

    This Stack Overflow quesion is the current top Google result for "random string Python". The current top answer is:

    ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N))
    

    This is an excellent method, but the PRNG in random is not cryptographically secure. I assume many people researching this question will want to generate random strings for encryption or passwords. You can do this securely by making a small change in the above code:

    ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(N))
    

    Using random.SystemRandom() instead of just random uses /dev/urandom on *nix machines and CryptGenRandom() in Windows. These are cryptographically secure PRNGs. Using random.choice instead of random.SystemRandom().choice in an application that requires a secure PRNG could be potentially devastating, and given the popularity of this question, I bet that mistake has been made many times already.

    If you're using python3.6 or above, you can use the new secrets module as mentioned in MSeifert's answer:

    ''.join(secrets.choice(string.ascii_uppercase + string.digits) for _ in range(N))
    

    The module docs also discuss convenient ways to generate secure tokens and best practices.

提交回复
热议问题