From e04cd17dc0b5e14f7c27b7ac4b64255a606ca8ea Mon Sep 17 00:00:00 2001 From: Filip Skokan Date: Sun, 26 Apr 2026 10:08:46 +0200 Subject: [PATCH] crypto: pass CryptoKey handles to KDF jobs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Pass CryptoKey handles directly into KDF jobs instead of exporting secret bytes in lib. Normalize HKDF, PBKDF2, and Argon2 around the same job construction pattern so WebCrypto derivation paths avoid extra key material copies and keep operation failures in native job handling. Signed-off-by: Filip Skokan PR-URL: https://github.com/nodejs/node/pull/63363 Reviewed-By: Antoine du Hamel Reviewed-By: René --- lib/internal/crypto/argon2.js | 18 +++-------------- lib/internal/crypto/hkdf.js | 20 +++++------------- lib/internal/crypto/pbkdf2.js | 16 ++------------- src/crypto/crypto_argon2.cc | 33 +++++++++++++++++++++++------- src/crypto/crypto_argon2.h | 2 ++ src/crypto/crypto_hkdf.cc | 37 +++++++++++++++++++++++++--------- src/crypto/crypto_hkdf.h | 1 + src/crypto/crypto_pbkdf2.cc | 38 ++++++++++++++++++++++++----------- src/crypto/crypto_pbkdf2.h | 4 +++- 9 files changed, 95 insertions(+), 74 deletions(-) diff --git a/lib/internal/crypto/argon2.js b/lib/internal/crypto/argon2.js index 08b16aa1411..6d9f9e462d0 100644 --- a/lib/internal/crypto/argon2.js +++ b/lib/internal/crypto/argon2.js @@ -211,28 +211,16 @@ function argon2DeriveBits(algorithm, baseKey, length) { 'Argon2id': kTypeArgon2id, }[algorithm.name]; - let message; - try { - // TODO(panva): call the job directly without needing to re-export the handle - message = getCryptoKeyHandle(baseKey).export(); - } catch (err) { - throw lazyDOMException( - 'The operation failed for an operation-specific reason', - { name: 'OperationError', cause: err }); - } - - const empty = new Uint8Array(0); - return jobPromise(() => new Argon2Job( kCryptoJobWebCrypto, - message, + getCryptoKeyHandle(baseKey), algorithm.nonce, algorithm.parallelism, length / 8, algorithm.memory, algorithm.passes, - algorithm.secretValue === undefined ? empty : algorithm.secretValue, - algorithm.associatedData === undefined ? empty : algorithm.associatedData, + algorithm.secretValue === undefined ? new Uint8Array() : algorithm.secretValue, + algorithm.associatedData === undefined ? new Uint8Array() : algorithm.associatedData, type)); } diff --git a/lib/internal/crypto/hkdf.js b/lib/internal/crypto/hkdf.js index a5443249481..73b16da6923 100644 --- a/lib/internal/crypto/hkdf.js +++ b/lib/internal/crypto/hkdf.js @@ -29,10 +29,9 @@ const { } = require('internal/crypto/util'); const { - createSecretKey, getCryptoKeyHandle, - getKeyObjectHandle, isKeyObject, + prepareSecretKey, } = require('internal/crypto/keys'); const { @@ -78,10 +77,10 @@ const validateParameters = hideStackFrames((hash, key, salt, info, length) => { function prepareKey(key) { if (isKeyObject(key)) - return getKeyObjectHandle(key); + return prepareSecretKey(key); if (isAnyArrayBuffer(key)) - return getKeyObjectHandle(createSecretKey(key)); + return key; key = toBuf(key); @@ -99,7 +98,7 @@ function prepareKey(key) { key); } - return getKeyObjectHandle(createSecretKey(key)); + return key; } function hkdf(hash, key, salt, info, length, callback) { @@ -157,18 +156,9 @@ function hkdfDeriveBits(algorithm, baseKey, length) { if (length === 0) return PromiseResolve(new ArrayBuffer(0)); - let normalizedHash; - try { - normalizedHash = normalizeHashName(hash.name); - } catch (err) { - throw lazyDOMException( - 'The operation failed for an operation-specific reason', - { name: 'OperationError', cause: err }); - } - return jobPromise(() => new HKDFJob( kCryptoJobWebCrypto, - normalizedHash, + normalizeHashName(hash.name), getCryptoKeyHandle(baseKey), salt, info, diff --git a/lib/internal/crypto/pbkdf2.js b/lib/internal/crypto/pbkdf2.js index 5cf4d8f46ec..87f763da9ba 100644 --- a/lib/internal/crypto/pbkdf2.js +++ b/lib/internal/crypto/pbkdf2.js @@ -114,25 +114,13 @@ function pbkdf2DeriveBits(algorithm, baseKey, length) { if (length === 0) return PromiseResolve(new ArrayBuffer(0)); - let password; - let normalizedHash; - try { - // TODO(panva): call the job directly without needing to re-export the handle - password = getCryptoKeyHandle(baseKey).export(); - normalizedHash = normalizeHashName(hash.name); - } catch (err) { - throw lazyDOMException( - 'The operation failed for an operation-specific reason', - { name: 'OperationError', cause: err }); - } - return jobPromise(() => new PBKDF2Job( kCryptoJobWebCrypto, - password, + getCryptoKeyHandle(baseKey), salt, iterations, length / 8, - normalizedHash)); + normalizeHashName(hash.name))); } module.exports = { diff --git a/src/crypto/crypto_argon2.cc b/src/crypto/crypto_argon2.cc index dd71f038f0c..42c5179f2b2 100644 --- a/src/crypto/crypto_argon2.cc +++ b/src/crypto/crypto_argon2.cc @@ -1,5 +1,8 @@ #include "crypto/crypto_argon2.h" #include "async_wrap-inl.h" +#include "base_object-inl.h" +#include "crypto/crypto_keys.h" +#include "memory_tracker-inl.h" #include "threadpoolwork-inl.h" #if OPENSSL_WITH_ARGON2 @@ -19,6 +22,7 @@ using v8::Value; Argon2Config::Argon2Config(Argon2Config&& other) noexcept : mode{other.mode}, + key{std::move(other.key)}, pass{std::move(other.pass)}, salt{std::move(other.salt)}, secret{std::move(other.secret)}, @@ -36,8 +40,9 @@ Argon2Config& Argon2Config::operator=(Argon2Config&& other) noexcept { } void Argon2Config::MemoryInfo(MemoryTracker* tracker) const { + if (key) tracker->TrackField("key", key); if (IsCryptoJobAsync(mode)) { - tracker->TrackFieldWithSize("pass", pass.size()); + if (!key) tracker->TrackFieldWithSize("pass", pass.size()); tracker->TrackFieldWithSize("salt", salt.size()); tracker->TrackFieldWithSize("secret", secret.size()); tracker->TrackFieldWithSize("ad", ad.size()); @@ -59,14 +64,23 @@ Maybe Argon2Traits::AdditionalConfig( config->mode = mode; - ArrayBufferOrViewContents pass(args[offset]); + CHECK(KeyObjectHandle::HasInstance(env, args[offset]) || + IsAnyBufferSource(args[offset])); // pass ArrayBufferOrViewContents salt(args[offset + 1]); ArrayBufferOrViewContents secret(args[offset + 6]); ArrayBufferOrViewContents ad(args[offset + 7]); - if (!pass.CheckSizeInt32()) [[unlikely]] { - THROW_ERR_OUT_OF_RANGE(env, "pass is too large"); - return Nothing(); + if (KeyObjectHandle::HasInstance(env, args[offset])) { + KeyObjectHandle* key; + ASSIGN_OR_RETURN_UNWRAP(&key, args[offset], Nothing()); + config->key = key->Data().addRef(); + } else { + ArrayBufferOrViewContents pass(args[offset]); + if (!pass.CheckSizeInt32()) [[unlikely]] { + THROW_ERR_OUT_OF_RANGE(env, "pass is too large"); + return Nothing(); + } + config->pass = IsCryptoJobAsync(mode) ? pass.ToCopy() : pass.ToByteSource(); } if (!salt.CheckSizeInt32()) [[unlikely]] { @@ -85,7 +99,6 @@ Maybe Argon2Traits::AdditionalConfig( } const bool isAsync = IsCryptoJobAsync(mode); - config->pass = isAsync ? pass.ToCopy() : pass.ToByteSource(); config->salt = isAsync ? salt.ToCopy() : salt.ToByteSource(); config->secret = isAsync ? secret.ToCopy() : secret.ToByteSource(); config->ad = isAsync ? ad.ToCopy() : ad.ToByteSource(); @@ -119,7 +132,13 @@ bool Argon2Traits::DeriveBits(Environment* env, } // Both the pass and salt may be zero-length at this point - auto dp = ncrypto::argon2(config.pass, + const ncrypto::Buffer pass{ + .data = config.key ? config.key.GetSymmetricKey() + : config.pass.data(), + .len = config.key ? config.key.GetSymmetricKeySize() : config.pass.size(), + }; + + auto dp = ncrypto::argon2(pass, config.salt, config.lanes, config.keylen, diff --git a/src/crypto/crypto_argon2.h b/src/crypto/crypto_argon2.h index 354d0a4be6f..058293805c0 100644 --- a/src/crypto/crypto_argon2.h +++ b/src/crypto/crypto_argon2.h @@ -3,6 +3,7 @@ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS +#include "crypto/crypto_keys.h" #include "crypto/crypto_util.h" namespace node::crypto { @@ -22,6 +23,7 @@ namespace node::crypto { struct Argon2Config final : public MemoryRetainer { CryptoJobMode mode; + KeyObjectData key; ByteSource pass; ByteSource salt; ByteSource secret; diff --git a/src/crypto/crypto_hkdf.cc b/src/crypto/crypto_hkdf.cc index fe12df11003..eb40ddad41c 100644 --- a/src/crypto/crypto_hkdf.cc +++ b/src/crypto/crypto_hkdf.cc @@ -24,6 +24,7 @@ HKDFConfig::HKDFConfig(HKDFConfig&& other) noexcept length(other.length), digest(other.digest), key(std::move(other.key)), + key_data(std::move(other.key_data)), salt(std::move(other.salt)), info(std::move(other.info)) {} @@ -49,7 +50,8 @@ Maybe HKDFTraits::AdditionalConfig( params->mode = mode; CHECK(args[offset]->IsString()); // Hash - CHECK(args[offset + 1]->IsObject()); // Key + CHECK(KeyObjectHandle::HasInstance(env, args[offset + 1]) || + IsAnyBufferSource(args[offset + 1])); // Key CHECK(IsAnyBufferSource(args[offset + 2])); // Salt CHECK(IsAnyBufferSource(args[offset + 3])); // Info CHECK(args[offset + 4]->IsUint32()); // Length @@ -61,9 +63,19 @@ Maybe HKDFTraits::AdditionalConfig( return Nothing(); } - KeyObjectHandle* key; - ASSIGN_OR_RETURN_UNWRAP(&key, args[offset + 1], Nothing()); - params->key = key->Data().addRef(); + if (KeyObjectHandle::HasInstance(env, args[offset + 1])) { + KeyObjectHandle* key; + ASSIGN_OR_RETURN_UNWRAP(&key, args[offset + 1], Nothing()); + params->key = key->Data().addRef(); + } else { + ArrayBufferOrViewContents key_data(args[offset + 1]); + if (!key_data.CheckSizeInt32()) [[unlikely]] { + THROW_ERR_OUT_OF_RANGE(env, "key is too big"); + return Nothing(); + } + params->key_data = + IsCryptoJobAsync(mode) ? key_data.ToCopy() : key_data.ToByteSource(); + } ArrayBufferOrViewContents salt(args[offset + 2]); ArrayBufferOrViewContents info(args[offset + 3]); @@ -98,12 +110,16 @@ bool HKDFTraits::DeriveBits(Environment* env, ByteSource* out, CryptoJobMode mode, CryptoErrorStore* errors) { + const ncrypto::Buffer key_data{ + .data = params.key ? reinterpret_cast( + params.key.GetSymmetricKey()) + : params.key_data.data(), + .len = params.key ? params.key.GetSymmetricKeySize() + : params.key_data.size(), + }; + auto dp = ncrypto::hkdf(params.digest, - ncrypto::Buffer{ - .data = reinterpret_cast( - params.key.GetSymmetricKey()), - .len = params.key.GetSymmetricKeySize(), - }, + key_data, ncrypto::Buffer{ .data = params.info.data(), .len = params.info.size(), @@ -124,9 +140,10 @@ bool HKDFTraits::DeriveBits(Environment* env, } void HKDFConfig::MemoryInfo(MemoryTracker* tracker) const { - tracker->TrackField("key", key); + if (key) tracker->TrackField("key", key); // If the job is sync, then the HKDFConfig does not own the data if (IsCryptoJobAsync(mode)) { + if (!key) tracker->TrackFieldWithSize("key", key_data.size()); tracker->TrackFieldWithSize("salt", salt.size()); tracker->TrackFieldWithSize("info", info.size()); } diff --git a/src/crypto/crypto_hkdf.h b/src/crypto/crypto_hkdf.h index 9f624d73dc1..bda6df63412 100644 --- a/src/crypto/crypto_hkdf.h +++ b/src/crypto/crypto_hkdf.h @@ -16,6 +16,7 @@ struct HKDFConfig final : public MemoryRetainer { size_t length; ncrypto::Digest digest; KeyObjectData key; + ByteSource key_data; ByteSource salt; ByteSource info; diff --git a/src/crypto/crypto_pbkdf2.cc b/src/crypto/crypto_pbkdf2.cc index b4bd02a4557..5c3fc438774 100644 --- a/src/crypto/crypto_pbkdf2.cc +++ b/src/crypto/crypto_pbkdf2.cc @@ -1,5 +1,7 @@ #include "crypto/crypto_pbkdf2.h" #include "async_wrap-inl.h" +#include "base_object-inl.h" +#include "crypto/crypto_keys.h" #include "crypto/crypto_util.h" #include "env-inl.h" #include "memory_tracker-inl.h" @@ -21,6 +23,7 @@ using v8::Value; namespace crypto { PBKDF2Config::PBKDF2Config(PBKDF2Config&& other) noexcept : mode(other.mode), + key(std::move(other.key)), pass(std::move(other.pass)), salt(std::move(other.salt)), iterations(other.iterations), @@ -34,9 +37,10 @@ PBKDF2Config& PBKDF2Config::operator=(PBKDF2Config&& other) noexcept { } void PBKDF2Config::MemoryInfo(MemoryTracker* tracker) const { - // The job is sync, the PBKDF2Config does not own the data. + // If the job is sync, PBKDF2Config does not own the data. + if (key) tracker->TrackField("key", key); if (IsCryptoJobAsync(mode)) { - tracker->TrackFieldWithSize("pass", pass.size()); + if (!key) tracker->TrackFieldWithSize("pass", pass.size()); tracker->TrackFieldWithSize("salt", salt.size()); } } @@ -63,12 +67,21 @@ Maybe PBKDF2Traits::AdditionalConfig( params->mode = mode; - ArrayBufferOrViewContents pass(args[offset]); + CHECK(KeyObjectHandle::HasInstance(env, args[offset]) || + IsAnyBufferSource(args[offset])); // pass ArrayBufferOrViewContents salt(args[offset + 1]); - if (!pass.CheckSizeInt32()) [[unlikely]] { - THROW_ERR_OUT_OF_RANGE(env, "pass is too large"); - return Nothing(); + if (KeyObjectHandle::HasInstance(env, args[offset])) { + KeyObjectHandle* key; + ASSIGN_OR_RETURN_UNWRAP(&key, args[offset], Nothing()); + params->key = key->Data().addRef(); + } else { + ArrayBufferOrViewContents pass(args[offset]); + if (!pass.CheckSizeInt32()) [[unlikely]] { + THROW_ERR_OUT_OF_RANGE(env, "pass is too large"); + return Nothing(); + } + params->pass = IsCryptoJobAsync(mode) ? pass.ToCopy() : pass.ToByteSource(); } if (!salt.CheckSizeInt32()) [[unlikely]] { @@ -76,8 +89,6 @@ Maybe PBKDF2Traits::AdditionalConfig( return Nothing(); } - params->pass = IsCryptoJobAsync(mode) ? pass.ToCopy() : pass.ToByteSource(); - params->salt = IsCryptoJobAsync(mode) ? salt.ToCopy() : salt.ToByteSource(); CHECK(args[offset + 2]->IsInt32()); // iteration_count @@ -112,11 +123,14 @@ bool PBKDF2Traits::DeriveBits(Environment* env, CryptoJobMode mode, CryptoErrorStore* errors) { // Both pass and salt may be zero length here. + const ncrypto::Buffer pass{ + .data = params.key ? params.key.GetSymmetricKey() + : params.pass.data(), + .len = params.key ? params.key.GetSymmetricKeySize() : params.pass.size(), + }; + auto dp = ncrypto::pbkdf2(params.digest, - ncrypto::Buffer{ - .data = params.pass.data(), - .len = params.pass.size(), - }, + pass, ncrypto::Buffer{ .data = params.salt.data(), .len = params.salt.size(), diff --git a/src/crypto/crypto_pbkdf2.h b/src/crypto/crypto_pbkdf2.h index 5ce3077e1af..639fb4293ee 100644 --- a/src/crypto/crypto_pbkdf2.h +++ b/src/crypto/crypto_pbkdf2.h @@ -3,8 +3,9 @@ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS -#include "crypto/crypto_util.h" #include "async_wrap.h" +#include "crypto/crypto_keys.h" +#include "crypto/crypto_util.h" #include "env.h" #include "memory_tracker.h" #include "v8.h" @@ -26,6 +27,7 @@ namespace crypto { struct PBKDF2Config final : public MemoryRetainer { CryptoJobMode mode; + KeyObjectData key; ByteSource pass; ByteSource salt; int32_t iterations;