Skip to main content
 首页 » 编程设计

python之我应该在 PyCrypto 2.0.1 的 RSA.generate() 中为 randfunc 使用什么

2025年05月04日16qq78292959

我正在尝试在 PyCrypto 的 2.0.1 和 2.6.1 版本中生成 RSA key 。

当我为 RSA.generate 指定单个参数时——位数,例如4096 – 例如下面的代码,在 2.6.1 版本中一切正常:

from Crypto.PublicKey import RSA 
keys = RSA.generate(4096) 

但是当我使用 PyCrypto 版本 2.0.1 运行它时,出现以下错误:

TypeError: generate_c() takes at least 2 arguments (1 given) 

我知道新的 API 有一个 randfunc=None,这就是它在 2.6.1 中工作的原因。

我的问题是我不知道 2.0.1 中可接受的 randfunc 是什么。我应该使用什么?

请您参考如下方法:

你应该使用 os.urandom。

引自PyCrypto documentation :

randfunc (callable) - Random number generation function; it should accept a single integer N and return a string of random data N bytes long. If not specified, a new one will be instantiated from Crypto.Random.

然后是“注意”部分:

You should always use a cryptographically secure random number generator, such as the one defined in the Crypto.Random module; don't just use the current time and the random module.

PyCrypto 2.0.1 中不存在 Crypto.Random 模块,因此您不能在此处使用此方法。相反,您应该使用 os.urandom() .引用文档(强调我的):

Return a string of n random bytes suitable for cryptographic use.

This function returns random bytes from an OS-specific randomness source. The returned data should be unpredictable enough for cryptographic applications, though its exact quality depends on the OS implementation. On a UNIX-like system this will query /dev/urandom, and on Windows it will use CryptGenRandom(). If a randomness source is not found, NotImplementedError will be raised.

对我来说,这听起来像是一个合适的 randfunc 选择。