From 47c54b29ba84f6dbbca3844ad262b329d0c4e72b Mon Sep 17 00:00:00 2001 From: James M Snell Date: Thu, 29 Aug 2024 17:04:42 -0700 Subject: [PATCH] src: move pbkdf2 to ncrypto --- deps/ncrypto/ncrypto.cc | 23 +++++++++++++++++++++++ deps/ncrypto/ncrypto.h | 6 ++++++ src/crypto/crypto_pbkdf2.cc | 26 ++++++++++---------------- 3 files changed, 39 insertions(+), 16 deletions(-) diff --git a/deps/ncrypto/ncrypto.cc b/deps/ncrypto/ncrypto.cc index 3e5d6a8924e00d..eb3533bb4623b1 100644 --- a/deps/ncrypto/ncrypto.cc +++ b/deps/ncrypto/ncrypto.cc @@ -1361,4 +1361,27 @@ DataPointer scrypt(const Buffer& pass, return {}; } +DataPointer pbkdf2(const EVP_MD* md, + const Buffer& pass, + const Buffer& salt, + uint32_t iterations, + size_t length) { + ClearErrorOnReturn clearErrorOnReturn; + + if (pass.len > INT_MAX || + salt.len > INT_MAX || + length > INT_MAX) { + return {}; + } + + auto dp = DataPointer::Alloc(length); + if (dp && PKCS5_PBKDF2_HMAC(pass.data, pass.len, salt.data, salt.len, + iterations, md, length, + reinterpret_cast(dp.get()))) { + return dp; + } + + return {}; +} + } // namespace ncrypto diff --git a/deps/ncrypto/ncrypto.h b/deps/ncrypto/ncrypto.h index a002831b4b01b3..60bfce3ea8999e 100644 --- a/deps/ncrypto/ncrypto.h +++ b/deps/ncrypto/ncrypto.h @@ -614,6 +614,12 @@ DataPointer scrypt(const Buffer& pass, uint64_t maxmem, size_t length); +DataPointer pbkdf2(const EVP_MD* md, + const Buffer& pass, + const Buffer& salt, + uint32_t iterations, + size_t length); + // ============================================================================ // Version metadata #define NCRYPTO_VERSION "0.0.1" diff --git a/src/crypto/crypto_pbkdf2.cc b/src/crypto/crypto_pbkdf2.cc index 963d0db6c62a45..645be2f10870a7 100644 --- a/src/crypto/crypto_pbkdf2.cc +++ b/src/crypto/crypto_pbkdf2.cc @@ -102,7 +102,7 @@ Maybe PBKDF2Traits::AdditionalConfig( } Utf8Value name(args.GetIsolate(), args[offset + 4]); - params->digest = EVP_get_digestbyname(*name); + params->digest = ncrypto::getDigestByName(name.ToStringView()); if (params->digest == nullptr) { THROW_ERR_CRYPTO_INVALID_DIGEST(env, "Invalid digest: %s", *name); return Nothing(); @@ -115,23 +115,17 @@ bool PBKDF2Traits::DeriveBits( Environment* env, const PBKDF2Config& params, ByteSource* out) { - ByteSource::Builder buf(params.length); // Both pass and salt may be zero length here. - // The generated bytes are stored in buf, which is - // assigned to out on success. - - if (PKCS5_PBKDF2_HMAC(params.pass.data(), - params.pass.size(), - params.salt.data(), - params.salt.size(), - params.iterations, - params.digest, - params.length, - buf.data()) <= 0) { - return false; - } - *out = std::move(buf).release(); + auto dp = ncrypto::pbkdf2( + params.digest, + ncrypto::Buffer(params.pass.data(), params.pass.size()), + ncrypto::Buffer(params.salt.data(), params.salt.size()), + params.iterations, + params.length); + + if (!dp) return false; + *out = ByteSource::Allocated(dp.release()); return true; }