random.randint生成加密安全的密钥

2024-06-16 11:17:02 发布

您现在位置:Python中文网/ 问答频道 /正文

此链接中的文档指出,randint不应用于生成加密密钥: https://docs.python.org/2/library/random.html

我试图理解为什么,以及如何能让攻击者破解基于这样一个密钥的密码系统。在


Tags: 文档httpsorg密码docs链接系统html
2条回答

Python使用伪随机数生成器(prng)创建“随机”数,供程序使用。这些数字是由看似随机的数学算法生成的。python使用的算法是mersennetwister。如文件所述:

Python uses the Mersenne Twister as the core generator. It produces 53-bit precision floats and has a period of 2**19937-1. The underlying implementation in C is both fast and threadsafe. The Mersenne Twister is one of the most extensively tested random number generators in existence. However, being completely deterministic, it is not suitable for all purposes, and is completely unsuitable for cryptographic purposes.

如前所述,该算法的目的是既快又尽可能“随机”。注意第二句话提到了算法的“句点”。因为计算机并不是完美的,只有有限的内存,所以基于这种算法,它们只能产生这么多的“随机”数字。句点是机器在开始重复之前可以达到的prng状态数(https://softwareengineering.stackexchange.com/questions/273105/why-is-the-period-of-a-pseudorandom-number-generator-important)。与此相结合,python根据运行程序的机器的内部特性来决定使用什么“状态”或使用什么“种子”。(参见随机.seed)在

random.seed(a=None)¶ Initialize internal state of the random number generator.

None or no argument seeds from current time or from an operating system specific randomness source if available (see the os.urandom() function for details on availability).

因此,攻击者可以使用暴力和运行应用程序的机器的基本知识,重新创建并确定程序中prng的顺序和未来状态。我绝不是psuedo随机数生成算法的专家,但希望这能让您对这个主题有一个了解:)

Pythonrandom模块使用基于时间的随机性,它是为建模和仿真而设计的,而不是安全性或密码学。在

攻击者可以理解密钥是何时创建的,这确实有助于他们潜在地暴力破解您的密钥。在

在python3中,您有一个secrets模块来解决这个问题。

secrets documenation

相关问题 更多 >