module OpenSSL::KDF

提供各种 KDF(密钥派生函数)的功能。

KDF 通常用于从密码安全地派生任意长度的对称密钥,这些密钥将与 OpenSSL::Cipher 一起使用。另一个用例是存储密码:通过增加迭代次数来调整计算量,可以人为地减慢计算速度,从而使可能的攻击变得不可行。

目前,OpenSSL::KDF 提供了以下 KDF 的实现

示例

Cipher(例如 AES)生成 128 位密钥

pass = "secret"
salt = OpenSSL::Random.random_bytes(16)
iter = 20_000
key_len = 16
key = OpenSSL::KDF.pbkdf2_hmac(pass, salt: salt, iterations: iter,
                               length: key_len, hash: "sha1")

存储密码

pass = "secret"
# store this with the generated value
salt = OpenSSL::Random.random_bytes(16)
iter = 20_000
hash = OpenSSL::Digest.new('SHA256')
len = hash.digest_length
# the final value to be stored
value = OpenSSL::KDF.pbkdf2_hmac(pass, salt: salt, iterations: iter,
                                 length: len, hash: hash)

关于检查密码的重要说明

在比较用户提供的密码与先前存储的值时,常见的错误是使用“==”比较两个值。“==”通常会在评估时短路,因此容易受到计时攻击。正确的方法是使用一种在比较两个值时始终花费相同时间的方法,从而不向潜在攻击者泄露任何信息。要做到这一点,请使用 OpenSSL.fixed_length_secure_compare