Commit 360bd63c6c5 for nodejs

commit 360bd63c6c56c160f9d96ae0b6e1fe65e555af92
Author: Filip Skokan <panva.ip@gmail.com>
Date:   Mon Nov 16 12:29:35 2026 +0100

    crypto: use settable parameter descriptors

    Resolve the exposed digest options against provider descriptors and
    construct UTF-8 or octet strings according to their advertised types.
    Keep binary values intact for octet strings and reject NUL bytes for
    UTF-8 strings.

    Share hash initialization and one-shot input/output handling while
    retaining the plain digest fast paths and XOF length checks. Probe RSA
    implicit rejection without changing its context.

    Signed-off-by: Filip Skokan <panva.ip@gmail.com>
    Assisted-by: Codex
    PR-URL: https://github.com/nodejs/node/pull/67565
    Reviewed-By: James M Snell <jasnell@gmail.com>
    Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com>

diff --git a/deps/ncrypto/ncrypto.cc b/deps/ncrypto/ncrypto.cc
index 001f366ce12..eef8a7b8da1 100644
--- a/deps/ncrypto/ncrypto.cc
+++ b/deps/ncrypto/ncrypto.cc
@@ -7079,18 +7079,16 @@ bool EVPKeyCtxPointer::setRsaPssSaltlen(int salt_len) {
   return EVP_PKEY_CTX_set_rsa_pss_keygen_saltlen(ctx_.get(), salt_len) > 0;
 }

-bool EVPKeyCtxPointer::setRsaImplicitRejection() {
+bool EVPKeyCtxPointer::supportsRsaImplicitRejection() const {
 #if NCRYPTO_USE_OPENSSL_PROVIDER
   if (!ctx_) return false;
-  return EVP_PKEY_CTX_ctrl_str(
-             ctx_.get(), "rsa_pkcs1_implicit_rejection", "1") > 0;
-  // From the doc -2 means that the option is not supported.
-  // The default for the option is enabled and if it has been
-  // specifically disabled we want to respect that so we will
-  // not throw an error if the option is supported regardless
-  // of how it is set. The call to set the value
-  // will not affect what is used since a different context is
-  // used in the call if the option is supported
+  const OSSL_PARAM* settable = EVP_PKEY_CTX_settable_params(ctx_.get());
+  // OSSL_ASYM_CIPHER_PARAM_IMPLICIT_REJECTION is not defined by OpenSSL 3.0.
+  const OSSL_PARAM* param =
+      settable == nullptr
+          ? nullptr
+          : OSSL_PARAM_locate_const(settable, "implicit-rejection");
+  return param != nullptr && param->data_type == OSSL_PARAM_UNSIGNED_INTEGER;
 #elif defined(OPENSSL_IS_BORINGSSL)
   // TODO(jasnell): Boringssl appears not to support this operation.
   // Is there an alternative approach that Boringssl does support?
diff --git a/deps/ncrypto/ncrypto.h b/deps/ncrypto/ncrypto.h
index 3e2ec991882..4261fc21bf1 100644
--- a/deps/ncrypto/ncrypto.h
+++ b/deps/ncrypto/ncrypto.h
@@ -1161,7 +1161,7 @@ class EVPKeyCtxPointer final {
   bool setRsaPssKeygenMd(const Digest& md);
   bool setRsaPssKeygenMgf1Md(const Digest& md);
   bool setRsaPssSaltlen(int salt_len);
-  bool setRsaImplicitRejection();
+  bool supportsRsaImplicitRejection() const;
   bool setRsaOaepLabel(DataPointer&& data);

   bool setSignatureMd(const EVPMDCtxPointer& md);
diff --git a/lib/internal/crypto/hash.js b/lib/internal/crypto/hash.js
index 35d57e2ae63..01c2771f79e 100644
--- a/lib/internal/crypto/hash.js
+++ b/lib/internal/crypto/hash.js
@@ -5,7 +5,6 @@ const {
   ObjectSetPrototypeOf,
   StringPrototypeToLowerCase,
   Symbol,
-  TypedArrayPrototypeIncludes,
 } = primordials;

 const {
@@ -28,7 +27,6 @@ const {
   getCachedHashId,
   getHashCache,
   getArrayBufferOrView,
-  getBufferSourceBytes,
   getOptionalByteLength,
 } = require('internal/crypto/util');

@@ -79,17 +77,6 @@ const emitHmacDigestDeprecation = getDeprecationWarningEmitter(
   'Calling Hmac.digest() more than once is deprecated.',
 );

-function normalizeCShakeParameter(value, name) {
-  if (value === undefined) return undefined;
-
-  value = getArrayBufferOrView(value, name);
-  if (TypedArrayPrototypeIncludes(getBufferSourceBytes(value), 0)) {
-    throw new ERR_INVALID_ARG_VALUE(
-      name, value, 'must not contain NUL bytes');
-  }
-  return value;
-}
-
 function Hash(privateSymbol, algorithm, options) {
   if (privateSymbol !== kPrivateConstructor)
     throw new ERR_ILLEGAL_CONSTRUCTOR();
@@ -108,12 +95,12 @@ function Hash(privateSymbol, algorithm, options) {
   if (!isCopy && options !== undefined && options !== null) {
     const functionNameOption = options.functionName;
     if (functionNameOption !== undefined) {
-      functionName = normalizeCShakeParameter(
+      functionName = getArrayBufferOrView(
         functionNameOption, 'options.functionName');
     }
     const customizationOption = options.customization;
     if (customizationOption !== undefined) {
-      customization = normalizeCShakeParameter(
+      customization = getArrayBufferOrView(
         customizationOption, 'options.customization');
     }
   }
@@ -345,12 +332,12 @@ function hash(algorithm, input, options) {
     outputEncoding = options.outputEncoding;
     const functionNameOption = options.functionName;
     if (functionNameOption !== undefined) {
-      functionName = normalizeCShakeParameter(
+      functionName = getArrayBufferOrView(
         functionNameOption, 'options.functionName');
     }
     const customizationOption = options.customization;
     if (customizationOption !== undefined) {
-      customization = normalizeCShakeParameter(
+      customization = getArrayBufferOrView(
         customizationOption, 'options.customization');
     }
   }
diff --git a/src/crypto/crypto_cipher.cc b/src/crypto/crypto_cipher.cc
index f28ecdae965..df3b890b35a 100644
--- a/src/crypto/crypto_cipher.cc
+++ b/src/crypto/crypto_cipher.cc
@@ -977,7 +977,7 @@ void PublicKeyCipher::Cipher(const FunctionCallbackInfo<Value>& args) {
     }

     // RSA implicit rejection here is not supported by BoringSSL.
-    if (!ctx.setRsaImplicitRejection()) [[unlikely]] {
+    if (!ctx.supportsRsaImplicitRejection()) [[unlikely]] {
       return THROW_ERR_INVALID_ARG_VALUE(
           env,
           "RSA_PKCS1_PADDING is no longer supported for private decryption");
diff --git a/src/crypto/crypto_hash.cc b/src/crypto/crypto_hash.cc
index e2c30eb7222..06ad8bff8b9 100644
--- a/src/crypto/crypto_hash.cc
+++ b/src/crypto/crypto_hash.cc
@@ -437,10 +437,21 @@ bool ShouldRejectMissingXofLength(const EVP_MD* md, size_t default_length) {
 #endif
 }

+void ThrowUnsupportedDigestOption(Environment* env,
+                                  Local<Value> algorithm,
+                                  const char* option) {
+  Utf8Value name(env->isolate(), algorithm);
+  THROW_ERR_INVALID_ARG_VALUE(
+      env,
+      "The property 'options.%s' is not supported by digest %s",
+      option,
+      *name);
+}
+
 void OneShotDigestWithMD(Environment* env,
                          const FunctionCallbackInfo<Value>& args,
                          const EVP_MD* md,
-                         const CShakeOptions* options) {
+                         const DigestOptions* options) {
   Isolate* isolate = env->isolate();
   if (md == nullptr) [[unlikely]] {
     Utf8Value method(isolate, args[0]);
@@ -492,69 +503,55 @@ void OneShotDigestWithMD(Environment* env,
     return return_empty_output();
   }

-  if (!has_digest_options) {
-    DataPointer output = ([&]() -> DataPointer {
-      if (args[3]->IsString()) {
-        Utf8Value utf8(isolate, args[3]);
-        ncrypto::Buffer<const unsigned char> input = {
-            .data = reinterpret_cast<const unsigned char*>(utf8.out()),
-            .len = static_cast<size_t>(utf8.length()),
-        };
-        return is_xof ? ncrypto::xofHashDigest(input, md, output_length)
-                      : ncrypto::hashDigest(input, md);
+  std::optional<EVPMDCtxPointer> ctx;
+  if (has_digest_options) {
+    ctx.emplace(EVPMDCtxPointer::New());
+    const char* unsupported_option = nullptr;
+    if (!options->Initialize(&*ctx, md, &unsupported_option)) {
+      if (unsupported_option != nullptr) {
+        return ThrowUnsupportedDigestOption(env, args[0], unsupported_option);
       }
-
-      ArrayBufferViewContents<unsigned char> input(args[3]);
-      ncrypto::Buffer<const unsigned char> buffer = {
-          .data = input.data(),
-          .len = input.length(),
-      };
-      return is_xof ? ncrypto::xofHashDigest(buffer, md, output_length)
-                    : ncrypto::hashDigest(buffer, md);
-    })();
-    if (!output) [[unlikely]] {
-      return ThrowCryptoError(env, ERR_get_error());
-    }
-
-    Local<Value> ret;
-    if (StringBytes::Encode(env->isolate(),
-                            static_cast<const char*>(output.get()),
-                            output.size(),
-                            output_enc)
-            .ToLocal(&ret)) {
-      args.GetReturnValue().Set(ret);
+      return ThrowCryptoError(
+          env, ERR_get_error(), "Digest options are not supported");
     }
-    return;
   }

-  EVPMDCtxPointer ctx = EVPMDCtxPointer::New();
-  if (!options->Initialize(&ctx, md)) {
-    return ThrowCryptoError(
-        env, ERR_get_error(), "Digest options are not supported");
-  }
-
-  const bool updated = [&]() {
+  bool updated = true;
+  auto digest_input =
+      [&](const ncrypto::Buffer<const unsigned char>& input) -> DataPointer {
+    if (has_digest_options) {
+      if (!ctx->digestUpdate(ncrypto::Buffer<const void>{
+              .data = input.data,
+              .len = input.len,
+          })) {
+        updated = false;
+        return {};
+      }
+      if (output_length == 0) return {};
+      return ctx->digestFinal(output_length);
+    }
+    return is_xof ? ncrypto::xofHashDigest(input, md, output_length)
+                  : ncrypto::hashDigest(input, md);
+  };
+  DataPointer output = [&]() -> DataPointer {
     if (args[3]->IsString()) {
       Utf8Value input(isolate, args[3]);
-      return ctx.digestUpdate(ncrypto::Buffer<const void>{
-          .data = input.out(),
+      return digest_input(ncrypto::Buffer<const unsigned char>{
+          .data = reinterpret_cast<const unsigned char*>(input.out()),
           .len = static_cast<size_t>(input.length()),
       });
     }

     ArrayBufferViewContents<unsigned char> input(args[3]);
-    return ctx.digestUpdate(ncrypto::Buffer<const void>{
+    return digest_input(ncrypto::Buffer<const unsigned char>{
         .data = input.data(),
         .len = input.length(),
     });
   }();
-  if (!updated) return ThrowCryptoError(env, ERR_get_error());
-  if (output_length == 0) return return_empty_output();
-  DataPointer output = ctx.digestFinal(output_length);
-
-  if (!output) [[unlikely]] {
+  if (!updated || (output_length != 0 && !output)) [[unlikely]] {
     return ThrowCryptoError(env, ERR_get_error());
   }
+  if (output_length == 0) return return_empty_output();

   Local<Value> ret;
   if (StringBytes::Encode(env->isolate(),
@@ -598,22 +595,17 @@ void Hash::OneShotDigest(const FunctionCallbackInfo<Value>& args) {
 #endif
   }

-  if (args.Length() == 9) {
-    CShakeOptions options;
-    if (GetCShakeOptions(args, 7, &options).IsNothing()) return;
-
-    std::optional<ncrypto::Digest> digest_owner;
-    const EVP_MD* md =
-        GetDigestImplementation(env, args[0], args[1], args[2], digest_owner);
-    if (env->isolate()->HasPendingException()) return;
-    return OneShotDigestWithMD(env, args, md, &options);
-  }
-
   std::optional<ncrypto::Digest> digest_owner;
   const EVP_MD* md =
       GetDigestImplementation(env, args[0], args[1], args[2], digest_owner);
   if (env->isolate()->HasPendingException()) return;
-  OneShotDigestWithMD(env, args, md, nullptr);
+
+  std::optional<DigestOptions> options;
+  if (args.Length() == 9) {
+    options.emplace();
+    if (GetDigestOptions(args, 7, md, &*options).IsNothing()) return;
+  }
+  OneShotDigestWithMD(env, args, md, options ? &*options : nullptr);
 }

 void Hash::Initialize(Environment* env, Local<Object> target) {
@@ -692,18 +684,20 @@ void Hash::New(const FunctionCallbackInfo<Value>& args) {
   }

   Hash* hash = new Hash(env, args.This());
-  if (args.Length() == 4) {
-    if (md == nullptr || !hash->HashInit(md, xof_md_len)) {
-      return ThrowCryptoError(
-          env, ERR_get_error(), "Digest method not supported");
-    }
-  } else {
-    CShakeOptions options;
-    if (GetCShakeOptions(args, 4, &options).IsNothing()) return;
-    if (md == nullptr || !hash->HashInit(md, options, xof_md_len)) {
-      return ThrowCryptoError(
-          env, ERR_get_error(), "Digest method not supported");
+  std::optional<DigestOptions> options;
+  if (args.Length() == 6) {
+    options.emplace();
+    if (GetDigestOptions(args, 4, md, &*options).IsNothing()) return;
+  }
+  const char* unsupported_option = nullptr;
+  if (md == nullptr ||
+      !hash->HashInit(
+          md, xof_md_len, options ? &*options : nullptr, &unsupported_option)) {
+    if (unsupported_option != nullptr) {
+      return ThrowUnsupportedDigestOption(env, args[0], unsupported_option);
     }
+    return ThrowCryptoError(
+        env, ERR_get_error(), "Digest method not supported");
   }

   if (orig != nullptr && !orig->mdctx_.copyTo(hash->mdctx_)) {
@@ -711,8 +705,20 @@ void Hash::New(const FunctionCallbackInfo<Value>& args) {
   }
 }

-bool Hash::FinishHashInit(const EVP_MD* digest,
-                          Maybe<unsigned int> xof_md_len) {
+bool Hash::HashInit(const EVP_MD* digest,
+                    Maybe<unsigned int> xof_md_len,
+                    const DigestOptions* options,
+                    const char** unsupported_option) {
+  mdctx_ = EVPMDCtxPointer::New();
+  const bool initialized =
+      options != nullptr
+          ? options->Initialize(&mdctx_, digest, unsupported_option)
+          : mdctx_.digestInit(digest);
+  if (!initialized) [[unlikely]] {
+    mdctx_.reset();
+    return false;
+  }
+
   md_len_ = mdctx_.getDigestSize();
   if (mdctx_.hasXofFlag() && !xof_md_len.IsJust() &&
       ShouldRejectMissingXofLength(digest, md_len_)) {
@@ -735,28 +741,6 @@ bool Hash::FinishHashInit(const EVP_MD* digest,
   return true;
 }

-bool Hash::HashInit(const EVP_MD* digest, Maybe<unsigned int> xof_md_len) {
-  mdctx_ = EVPMDCtxPointer::New();
-  if (!mdctx_.digestInit(digest)) [[unlikely]] {
-    mdctx_.reset();
-    return false;
-  }
-
-  return FinishHashInit(digest, xof_md_len);
-}
-
-bool Hash::HashInit(const EVP_MD* digest,
-                    const CShakeOptions& options,
-                    Maybe<unsigned int> xof_md_len) {
-  mdctx_ = EVPMDCtxPointer::New();
-  if (!options.Initialize(&mdctx_, digest)) [[unlikely]] {
-    mdctx_.reset();
-    return false;
-  }
-
-  return FinishHashInit(digest, xof_md_len);
-}
-
 bool Hash::HashUpdate(const char* data, size_t len) {
   if (!mdctx_) return false;
   return mdctx_.digestUpdate(ncrypto::Buffer<const void>{
@@ -879,7 +863,9 @@ Maybe<void> HashTraits::AdditionalConfig(

   if (static_cast<unsigned int>(args.Length()) > offset + 3) {
     params->options.emplace();
-    if (GetCShakeOptions(args, offset + 3, &*params->options).IsNothing()) {
+    if (GetDigestOptions(
+            args, offset + 3, params->digest.get(), &*params->options)
+            .IsNothing()) {
       return Nothing<void>();
     }
   }
diff --git a/src/crypto/crypto_hash.h b/src/crypto/crypto_hash.h
index 558c67822f4..1f55017d8c0 100644
--- a/src/crypto/crypto_hash.h
+++ b/src/crypto/crypto_hash.h
@@ -39,10 +39,10 @@ class Hash final : public BaseObject {
   SET_MEMORY_INFO_NAME(Hash)
   SET_SELF_SIZE(Hash)

-  bool HashInit(const EVP_MD* digest, v8::Maybe<unsigned int> xof_md_len);
   bool HashInit(const EVP_MD* digest,
-                const CShakeOptions& options,
-                v8::Maybe<unsigned int> xof_md_len);
+                v8::Maybe<unsigned int> xof_md_len,
+                const DigestOptions* options = nullptr,
+                const char** unsupported_option = nullptr);
   bool HashUpdate(const char* data, size_t len);

   static void GetHashes(const v8::FunctionCallbackInfo<v8::Value>& args);
@@ -57,11 +57,6 @@ class Hash final : public BaseObject {
   Hash(Environment* env, v8::Local<v8::Object> wrap);

  private:
-  // Determines the digest length after mdctx_ has been initialized, applying
-  // and validating the requested XOF output length. Resets mdctx_ and returns
-  // false on failure.
-  bool FinishHashInit(const EVP_MD* digest, v8::Maybe<unsigned int> xof_md_len);
-
   ncrypto::EVPMDCtxPointer mdctx_{};
   unsigned int md_len_ = 0;
   ByteSource digest_;
@@ -70,7 +65,7 @@ class Hash final : public BaseObject {
 struct HashConfig final : public MemoryRetainer {
   ByteSource in;
   ncrypto::Digest digest;
-  std::optional<CShakeOptions> options;
+  std::optional<DigestOptions> options;
   unsigned int length;

   HashConfig() = default;
diff --git a/src/crypto/crypto_util.cc b/src/crypto/crypto_util.cc
index 09f5353d52f..b8aa47adda4 100644
--- a/src/crypto/crypto_util.cc
+++ b/src/crypto/crypto_util.cc
@@ -83,108 +83,107 @@ size_t MemoryRetainerTraits<crypto::ByteSource>::SelfSize(

 namespace crypto {

-CShakeOptions::CShakeOptions(CShakeOptions&& other) noexcept
-    : function_name(std::move(other.function_name)),
-      customization(std::move(other.customization)),
-      flags(other.flags) {}
-
-CShakeOptions& CShakeOptions::operator=(CShakeOptions&& other) noexcept {
-  if (&other == this) return *this;
-  this->~CShakeOptions();
-  return *new (this) CShakeOptions(std::move(other));
-}
-
-void CShakeOptions::MemoryInfo(MemoryTracker* tracker) const {
-  tracker->TrackFieldWithSize("function_name", function_name.size());
-  tracker->TrackFieldWithSize("customization", customization.size());
+void DigestOptions::MemoryInfo(MemoryTracker* tracker) const {
+  for (size_t i = 0; i < values.size(); i++) {
+    if (values[i].has_value()) {
+      tracker->TrackFieldWithSize(kParameters[i].key, values[i]->size());
+    }
+  }
 }

-bool CShakeOptions::Initialize(ncrypto::EVPMDCtxPointer* ctx,
-                               const EVP_MD* digest) const {
+bool DigestOptions::Initialize(ncrypto::EVPMDCtxPointer* ctx,
+                               const EVP_MD* digest,
+                               const char** unsupported_option) const {
   if (!ctx || !*ctx || digest == nullptr) return false;
   if (empty()) return ctx->digestInit(digest);

+  auto unsupported = [unsupported_option](size_t i) {
+    if (unsupported_option != nullptr) {
+      *unsupported_option = kParameters[i].name;
+    }
+    return false;
+  };
+
 #if NCRYPTO_USE_OPENSSL_PROVIDER
-  const bool is_cshake =
-      EVP_MD_is_a(digest, "CSHAKE-128") || EVP_MD_is_a(digest, "CSHAKE-256");
-  if (!is_cshake) return false;
+  const OSSL_PARAM* settable = EVP_MD_settable_ctx_params(digest);

-  OSSL_PARAM params[3];
+  std::array<OSSL_PARAM, kParameters.size() + 1> params;
   size_t count = 0;
-  if (has(kFunctionName)) {
-    params[count++] = OSSL_PARAM_construct_utf8_string(
-        "function-name",
-        const_cast<char*>(function_name.c_str()),
-        function_name.size());
-  }
-  if (has(kCustomization)) {
-    params[count++] = OSSL_PARAM_construct_utf8_string(
-        "customization",
-        const_cast<char*>(customization.c_str()),
-        customization.size());
+  for (size_t i = 0; i < values.size(); i++) {
+    if (!values[i].has_value()) continue;
+    const char* key = kParameters[i].key;
+    const std::string& value = *values[i];
+    const OSSL_PARAM* descriptor =
+        settable == nullptr ? nullptr : OSSL_PARAM_locate_const(settable, key);
+    if (descriptor == nullptr) return unsupported(i);
+    switch (descriptor->data_type) {
+      case OSSL_PARAM_UTF8_STRING:
+        if (value.find('\0') != std::string::npos) return false;
+        params[count++] = OSSL_PARAM_construct_utf8_string(
+            key, const_cast<char*>(value.c_str()), value.size());
+        break;
+      case OSSL_PARAM_OCTET_STRING:
+        params[count++] = OSSL_PARAM_construct_octet_string(
+            key, const_cast<char*>(value.data()), value.size());
+        break;
+      default:
+        return unsupported(i);
+    }
   }
   params[count] = OSSL_PARAM_construct_end();
-  return ctx->digestInit(digest, params);
-#elif defined(OPENSSL_IS_BORINGSSL)
-  // BoringSSL does not support these cSHAKE parameters.
-  return false;
+  return ctx->digestInit(digest, params.data());
+#elif NCRYPTO_USE_BORINGSSL
+  // BoringSSL does not support these digest parameters.
+  for (size_t i = 0; i < values.size(); i++) {
+    if (values[i].has_value()) return unsupported(i);
+  }
+  UNREACHABLE();
 #else
 #error "Unsupported crypto backend"
 #endif
 }

 namespace {
-bool ContainsNullByte(std::string_view value) {
-  return value.find('\0') != std::string_view::npos;
-}
-
-v8::Maybe<void> GetDigestStringOption(
-    Environment* env,
-    const v8::FunctionCallbackInfo<v8::Value>& args,
-    unsigned int offset,
-    CShakeOptions::Flag flag,
-    std::string* target,
-    CShakeOptions* options) {
-  if (args[offset]->IsUndefined()) return v8::JustVoid();
-  CHECK(IsAnyBufferSource(args[offset]));
-  ArrayBufferOrViewContents<char> value(args[offset]);
-  if (!value.CheckSizeInt32()) {
-    THROW_ERR_OUT_OF_RANGE(env, "digest option is too big");
-    return v8::Nothing<void>();
-  }
-  target->assign(value.data(), value.size());
-  if (ContainsNullByte(*target)) {
-    THROW_ERR_INVALID_ARG_VALUE(env,
-                                "Digest options must not contain null bytes");
-    return v8::Nothing<void>();
-  }
-  options->flags |= flag;
-  return v8::JustVoid();
+bool IsOctetParameter(const EVP_MD* digest, const char* name) {
+#if NCRYPTO_USE_OPENSSL_PROVIDER
+  if (digest == nullptr) return false;
+  const OSSL_PARAM* params = EVP_MD_settable_ctx_params(digest);
+  const OSSL_PARAM* descriptor =
+      params == nullptr ? nullptr : OSSL_PARAM_locate_const(params, name);
+  return descriptor != nullptr &&
+         descriptor->data_type == OSSL_PARAM_OCTET_STRING;
+#elif NCRYPTO_USE_BORINGSSL
+  static_cast<void>(digest);
+  static_cast<void>(name);
+  return false;
+#else
+#error "Unsupported crypto backend"
+#endif
 }
 }  // namespace

-v8::Maybe<void> GetCShakeOptions(
+v8::Maybe<void> GetDigestOptions(
     const v8::FunctionCallbackInfo<v8::Value>& args,
     unsigned int offset,
-    CShakeOptions* options) {
+    const EVP_MD* digest,
+    DigestOptions* options) {
   Environment* env = Environment::GetCurrent(args);
-  if (GetDigestStringOption(env,
-                            args,
-                            offset,
-                            CShakeOptions::kFunctionName,
-                            &options->function_name,
-                            options)
-          .IsNothing() ||
-      GetDigestStringOption(env,
-                            args,
-                            offset + 1,
-                            CShakeOptions::kCustomization,
-                            &options->customization,
-                            options)
-          .IsNothing()) {
-    return v8::Nothing<void>();
+  for (size_t i = 0; i < DigestOptions::kParameters.size(); i++) {
+    if (args[offset + i]->IsUndefined()) continue;
+    CHECK(IsAnyBufferSource(args[offset + i]));
+    ArrayBufferOrViewContents<char> value(args[offset + i]);
+    if (!value.CheckSizeInt32()) {
+      THROW_ERR_OUT_OF_RANGE(env, "digest option is too big");
+      return v8::Nothing<void>();
+    }
+    std::string& bytes = options->values[i].emplace(value.data(), value.size());
+    if (bytes.find('\0') != std::string::npos &&
+        !IsOctetParameter(digest, DigestOptions::kParameters[i].key)) {
+      THROW_ERR_INVALID_ARG_VALUE(env,
+                                  "Digest options must not contain null bytes");
+      return v8::Nothing<void>();
+    }
   }
-
   return v8::JustVoid();
 }

diff --git a/src/crypto/crypto_util.h b/src/crypto/crypto_util.h
index 95980b1250f..f39ae6feff7 100644
--- a/src/crypto/crypto_util.h
+++ b/src/crypto/crypto_util.h
@@ -15,6 +15,7 @@
 #include "ncrypto.h"

 #include <algorithm>
+#include <array>
 #include <climits>
 #include <cstdio>
 #include <memory>
@@ -300,34 +301,42 @@ enum CryptoJobMode { kCryptoJobAsync, kCryptoJobSync, kCryptoJobWebCrypto };
 CryptoJobMode GetCryptoJobMode(v8::Local<v8::Value> args);
 bool IsCryptoJobAsync(CryptoJobMode mode);

-struct CShakeOptions final : public MemoryRetainer {
-  enum Flag : uint8_t {
-    kFunctionName = 1 << 0,
-    kCustomization = 1 << 1,
+struct DigestOptions final : public MemoryRetainer {
+  struct Parameter {
+    const char* name;
+    const char* key;
   };
+  static constexpr std::array kParameters = {
+      Parameter{"functionName", "function-name"},
+      Parameter{"customization", "customization"},
+  };
+  std::array<std::optional<std::string>, kParameters.size()> values;

-  std::string function_name;
-  std::string customization;
-  uint8_t flags = 0;
-
-  CShakeOptions() = default;
-  CShakeOptions(CShakeOptions&& other) noexcept;
-  CShakeOptions& operator=(CShakeOptions&& other) noexcept;
+  DigestOptions() = default;
+  DigestOptions(DigestOptions&& other) noexcept = default;
+  DigestOptions& operator=(DigestOptions&& other) noexcept = default;

-  bool empty() const { return flags == 0; }
-  bool has(Flag flag) const { return (flags & flag) != 0; }
+  bool empty() const {
+    for (const auto& value : values) {
+      if (value.has_value()) return false;
+    }
+    return true;
+  }

-  bool Initialize(ncrypto::EVPMDCtxPointer* ctx, const EVP_MD* digest) const;
+  bool Initialize(ncrypto::EVPMDCtxPointer* ctx,
+                  const EVP_MD* digest,
+                  const char** unsupported_option = nullptr) const;

   void MemoryInfo(MemoryTracker* tracker) const override;
-  SET_MEMORY_INFO_NAME(CShakeOptions)
-  SET_SELF_SIZE(CShakeOptions)
+  SET_MEMORY_INFO_NAME(DigestOptions)
+  SET_SELF_SIZE(DigestOptions)
 };

-v8::Maybe<void> GetCShakeOptions(
+v8::Maybe<void> GetDigestOptions(
     const v8::FunctionCallbackInfo<v8::Value>& args,
     unsigned int offset,
-    CShakeOptions* options);
+    const EVP_MD* digest,
+    DigestOptions* options);

 v8::MaybeLocal<v8::Value> CreateWebCryptoJobError(Environment* env,
                                                   v8::Local<v8::Value> cause);
diff --git a/test/parallel/test-crypto-hash.js b/test/parallel/test-crypto-hash.js
index 8e5f0eb47fa..981e7a16866 100644
--- a/test/parallel/test-crypto-hash.js
+++ b/test/parallel/test-crypto-hash.js
@@ -114,6 +114,21 @@ assert.throws(function() {
   crypto.createHash('xyzzy');
 }, /Digest method not supported/);

+for (const [option, value] of [
+  ['functionName', 'KMAC'],
+  ['customization', 'Node.js'],
+  ['functionName', Buffer.alloc(0)],
+  ['customization', new Uint8Array(0)],
+]) {
+  const options = { [option]: value };
+  const expected = {
+    code: 'ERR_INVALID_ARG_VALUE',
+    message: `The property 'options.${option}' is not supported by digest sha256`,
+  };
+  assert.throws(() => crypto.createHash('sha256', options), expected);
+  assert.throws(() => crypto.hash('sha256', 'abc', options), expected);
+}
+
 // Issue https://github.com/nodejs/node/issues/9819: throwing encoding used to
 // segfault.
 assert.throws(
diff --git a/test/parallel/test-crypto-provider-hash-options.js b/test/parallel/test-crypto-provider-hash-options.js
index 997b179413a..256bfe598eb 100644
--- a/test/parallel/test-crypto-provider-hash-options.js
+++ b/test/parallel/test-crypto-provider-hash-options.js
@@ -366,24 +366,6 @@ for (const vector of cshakeVectors) {
   }
 }

-if (cshakeVectors.some(({ names }) => findHash(...names) !== undefined)) {
-  for (const mismatchedOptions of [
-    { functionName: 'KMAC' },
-    { customization: 'Node.js' },
-    { functionName: Buffer.alloc(0) },
-    { customization: new Uint8Array(0) },
-  ]) {
-    assert.throws(
-      () => createHash('sha256', mismatchedOptions),
-      { message: 'Digest method not supported' },
-    );
-    assert.throws(
-      () => hash('sha256', Buffer.from('abc'), mismatchedOptions),
-      { message: 'Digest options are not supported' },
-    );
-  }
-}
-
 if (!exercised) {
   common.printSkipMessage('cSHAKE is not available');
 }