PostgreSQL /dev/urandom

PostgreSQL /dev/urandom

是否有一个 PostgreSQL 函数可以用来生成 160 位随机数 /dev/urandom

我们想要生成访问令牌。

根据 OAuth 2.0 Authorization Framework: 10.10. Credentials-Guessing Attacks:

The probability of an attacker guessing generated tokens (and other credentials not intended for handling by end-users) MUST be less than or equal to 2^(-128) and SHOULD be less than or equal to 2^(-160).

正如 pozs 所说,您可以使用 pgcrypto contrib 模块中的 gen_random_bytes(int)

此函数从 src/port/pg_strong_random.c 调用 pg_strong_random 并在 return 代码为 false 时抛出错误。

评论解释了 pg_strong_random 的工作原理:

 * Generate requested number of random bytes. The returned bytes are
 * cryptographically secure, suitable for use e.g. in authentication.
 *
 * We rely on system facilities for actually generating the numbers.
 * We support a number of sources:
 *
 * 1. OpenSSL's RAND_bytes()
 * 2. Windows' CryptGenRandom() function
 * 3. /dev/urandom
 *
 * The configure script will choose which one to use, and set
 * a USE_*_RANDOM flag accordingly.
 *
 * Returns true on success, and false if none of the sources
 * were available. NB: It is important to check the return value!

您可以在您的 PostgreSQL 安装中查看 include/pg_config.h 并查看使用了哪个随机数源。

如果您使用 Linux,您可能会使用 OpenSSL 作为随机源。

manual page for RAND_bytes 声明:

RAND_bytes() puts num cryptographically strong pseudo-random bytes into buf.

我没有深入研究 OpenSSL 源代码,因为那真的很伤人,但本质上,如果您信任 OpenSSL,那么您也可以信任 pgcrypto