IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    用一行python生成随机字符串

    羽墨发表于 2015-03-07 01:17:44
    love 0

    在stackoverflow上看到这样的问题:

    需要用python生成由数字和大写字母组成的随机字符串,如:

    • 6U1S75
    • 4Z4UKK
    • U911K4

    这个需求可以用一行python语句解决:

    ''.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.uppercase + string.digits) for _ in xrange(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.



沪ICP备19023445号-2号
友情链接