【问题标题】:How to use Python `secret` module to generate random integer?如何使用 Python `secret` 模块生成随机整数?
【发布时间】:2016-12-06 17:43:04
【问题描述】:

在 Python 3.6 中,添加了 new module, secrets。

使用此模块在[n, m) 范围内生成随机整数的最有效方法是什么?

我试过choice(range(n, m)),但我怀疑这是最好的方法。

【问题讨论】:

    标签: python security random python-3.6


    【解决方案1】:

    secrets.choice(range(n, m)) 应该没问题,因为range 在 Python 3 上是惰性的。

    n + secrets.randbelow(m-n) 是另一种选择。我不会使用它,因为它不太明显是正确的。

    由于secrets 提供对SystemRandom 类的访问,与random.Random 具有相同的接口,您也可以保留自己的SystemRandom 实例:

    my_secure_rng = secrets.SystemRandom()
    

    然后做

    my_secure_rng.randrange(n, m)
    

    【讨论】:

    • my_secure_rng.randrange(1000, 9999) 如何生成没有所有相同数字的4位数字?我需要一个除 1111,2222,3333,4444,5555,6666,7777,8888,9999 之外的数字。
    【解决方案2】:

    secret 模块提供与random 相同的接口;底层随机生成器刚刚更改为SystemRandom,这在密码学上很强大。

    简而言之,在需要更多安全性的情况下,可以像 random 一样使用它;我怀疑choice 的性能受到如此严重的影响,值得您关注。

    【讨论】:

      【解决方案3】:
      import secrets
      num = secrets.randbelow(50)
      print(num)
      

      【讨论】:

      • 请多解释。
      【解决方案4】:

      没有足够的代表发表评论,但如果您运行快速执行时间测试,他们实际上报告基本相同。

      Best of 3 trials with 1,000,000 loops per trial:
              randrange() 1.39906 seconds total time.
              choice() 1.39431 seconds total time.
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-08-06
        • 2011-05-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-15
        相关资源
        最近更新 更多