Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
OpenSSL::KDF.pbkdf2_hmac
static VALUE
kdf_pbkdf2_hmac(int argc, VALUE *argv, VALUE self)
{
VALUE pass, salt, opts, kwargs[4], str, md_holder, pass_tmp, salt_tmp;
static ID kwargs_ids[4];
int passlen, saltlen, iters, len;
const EVP_MD *md;
if (!kwargs_ids[0]) {
kwargs_ids[0] = rb_intern_const("salt");
kwargs_ids[1] = rb_intern_const("iterations");
kwargs_ids[2] = rb_intern_const("length");
kwargs_ids[3] = rb_intern_const("hash");
}
rb_scan_args(argc, argv, "1:", &pass, &opts);
rb_get_kwargs(opts, kwargs_ids, 4, 0, kwargs);
StringValue(pass);
salt = StringValue(kwargs[0]);
iters = NUM2INT(kwargs[1]);
len = NUM2INT(kwargs[2]);
md = ossl_evp_md_fetch(kwargs[3], &md_holder);
passlen = RSTRING_LENINT(pass);
saltlen = RSTRING_LENINT(salt);
str = rb_str_new(NULL, len);
struct pbkdf2_hmac_args args = {
.pass = ALLOCV(pass_tmp, passlen),
.passlen = passlen,
.salt = ALLOCV(salt_tmp, saltlen),
.saltlen = saltlen,
.iters = iters,
.md = md,
.len = len,
.out = (unsigned char *)RSTRING_PTR(str),
};
memcpy(args.pass, RSTRING_PTR(pass), passlen);
memcpy(args.salt, RSTRING_PTR(salt), saltlen);
if (!rb_thread_call_without_gvl(pbkdf2_hmac_nogvl, &args, NULL, NULL))
ossl_raise(eKDF, "PKCS5_PBKDF2_HMAC");
OPENSSL_cleanse(args.pass, passlen);
ALLOCV_END(pass_tmp);
ALLOCV_END(salt_tmp);
return str;
}
PKCS #5 PBKDF2 (Password-Based Key Derivation Function 2) in combination with HMAC. Takes pass, salt and iterations, and then derives a key of length bytes.
For more information about PBKDF2, see RFC 2898 Section 5.2 (www.rfc-editor.org/rfc/rfc2898#section-5.2).
NOTE: This method cannot be interrupted by Timeout.timeout from the “timeout” library. Do not take parameters from untrusted sources without enforcing reasonable limits.
Parameters
- pass
-
The password.
- salt
-
The salt. Salts prevent attacks based on dictionaries of common passwords and attacks based on rainbow tables. It is a public value that can be safely stored along with the password (e.g. if the derived value is used for password storage).
- iterations
-
The iteration count. This provides the ability to tune the algorithm. It is better to use the highest count possible for the maximum resistance to brute-force attacks.
- length
-
The desired length of the derived key in octets.
- hash
-
The hash algorithm used with
HMACfor the PRF. May be aStringrepresenting the algorithm name, or an instance ofOpenSSL::Digest.