Commit c54c94839d7 for nodejs

commit c54c94839d72381b826c8d7dd22504248a761548
Author: Filip Skokan <panva.ip@gmail.com>
Date:   Mon Nov 16 13:09:49 2026 +0100

    crypto: simplify MAC and signature options

    Build exposed MAC parameters from one option table and their advertised
    types. Keep binary octet values and terminated UTF-8 strings.

    Share sign/verify initialization and replace padding and salt length
    presence flags with optional values. Pass context parameters during
    initialization and retain backend-specific handling.

    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 eef8a7b8da1..29391ba531d 100644
--- a/deps/ncrypto/ncrypto.cc
+++ b/deps/ncrypto/ncrypto.cc
@@ -8290,128 +8290,74 @@ bool EVPMDCtxPointer::copyTo(const EVPMDCtxPointer& other) const {
   return true;
 }

-std::optional<EVP_PKEY_CTX*> EVPMDCtxPointer::signInit(const EVPKeyPointer& key,
-                                                       const Digest& digest) {
-  EVP_PKEY_CTX* ctx = nullptr;
-  if (!EVP_DigestSignInit(ctx_.get(), &ctx, digest, nullptr, key.get())) {
-    return std::nullopt;
-  }
-  return ctx;
-}
-
-std::optional<EVP_PKEY_CTX*> EVPMDCtxPointer::verifyInit(
-    const EVPKeyPointer& key, const Digest& digest) {
-  EVP_PKEY_CTX* ctx = nullptr;
-  if (!EVP_DigestVerifyInit(ctx_.get(), &ctx, digest, nullptr, key.get())) {
-    return std::nullopt;
-  }
-  return ctx;
-}
+namespace {
+enum class SignatureOperation { Sign, Verify };

-std::optional<EVP_PKEY_CTX*> EVPMDCtxPointer::signInitWithContext(
+template <SignatureOperation operation>
+std::optional<EVP_PKEY_CTX*> InitializeSignature(
+    EVP_MD_CTX* mdctx,
     const EVPKeyPointer& key,
     const Digest& digest,
-    const Buffer<const unsigned char>& context_string) {
-#ifdef OPENSSL_IS_BORINGSSL
+    const Buffer<const unsigned char>* context_string) {
+  constexpr auto init = operation == SignatureOperation::Sign
+                            ? EVP_DigestSignInit
+                            : EVP_DigestVerifyInit;
   EVP_PKEY_CTX* ctx = nullptr;
-  if (!EVP_DigestSignInit(ctx_.get(), &ctx, digest, nullptr, key.get())) {
-    return std::nullopt;
+  if (context_string == nullptr) {
+    if (!init(mdctx, &ctx, digest, nullptr, key.get())) return std::nullopt;
+    return ctx;
   }
-  if (EVP_PKEY_CTX_set1_signature_context_string(
-          ctx, context_string.data, context_string.len) <= 0) {
+
+#if NCRYPTO_USE_BORINGSSL
+  if (!init(mdctx, &ctx, digest, nullptr, key.get()) ||
+      EVP_PKEY_CTX_set1_signature_context_string(
+          ctx, context_string->data, context_string->len) <= 0) {
     return std::nullopt;
   }
-  return ctx;
 #elif NCRYPTO_USE_OPENSSL_PROVIDER
-  EVP_PKEY_CTX* ctx = nullptr;
-
-  // Ed25519 requires the INSTANCE param to switch into Ed25519ctx mode.
+  std::array<OSSL_PARAM, 3> params;
+  size_t count = 0;
+  // Ed25519 requires the instance parameter to switch into Ed25519ctx mode.
   // Without it, OpenSSL silently ignores the context string.
   if (key.isA(KeyAlgorithm::ED25519)) {
-    const OSSL_PARAM params[] = {
-        OSSL_PARAM_construct_utf8_string(
-            kSignatureInstance, const_cast<char*>("Ed25519ctx"), 0),
-        OSSL_PARAM_construct_octet_string(
-            kSignatureContextString,
-            const_cast<unsigned char*>(context_string.data),
-            context_string.len),
-        OSSL_PARAM_END};
-
-    if (!EVP_DigestSignInit_ex(
-            ctx_.get(), &ctx, nullptr, nullptr, nullptr, key.get(), params)) {
-      return std::nullopt;
-    }
-    return ctx;
-  }
-
-  const OSSL_PARAM params[] = {
-      OSSL_PARAM_construct_octet_string(
-          kSignatureContextString,
-          const_cast<unsigned char*>(context_string.data),
-          context_string.len),
-      OSSL_PARAM_END};
-
-  if (!EVP_DigestSignInit_ex(
-          ctx_.get(), &ctx, nullptr, nullptr, nullptr, key.get(), params)) {
+    params[count++] = OSSL_PARAM_construct_utf8_string(
+        kSignatureInstance, const_cast<char*>("Ed25519ctx"), 0);
+  }
+  params[count++] = OSSL_PARAM_construct_octet_string(
+      kSignatureContextString,
+      const_cast<unsigned char*>(context_string->data),
+      context_string->len);
+  params[count] = OSSL_PARAM_END;
+
+  constexpr auto init_ex = operation == SignatureOperation::Sign
+                               ? EVP_DigestSignInit_ex
+                               : EVP_DigestVerifyInit_ex;
+  // Preserve the context-taking provider path's implicit digest selection.
+  if (!init_ex(
+          mdctx, &ctx, nullptr, nullptr, nullptr, key.get(), params.data())) {
     return std::nullopt;
   }
-  return ctx;
 #else
 #error "Unsupported crypto backend"
 #endif
+  return ctx;
 }
+}  // namespace

-std::optional<EVP_PKEY_CTX*> EVPMDCtxPointer::verifyInitWithContext(
+std::optional<EVP_PKEY_CTX*> EVPMDCtxPointer::signInit(
     const EVPKeyPointer& key,
     const Digest& digest,
-    const Buffer<const unsigned char>& context_string) {
-#ifdef OPENSSL_IS_BORINGSSL
-  EVP_PKEY_CTX* ctx = nullptr;
-  if (!EVP_DigestVerifyInit(ctx_.get(), &ctx, digest, nullptr, key.get())) {
-    return std::nullopt;
-  }
-  if (EVP_PKEY_CTX_set1_signature_context_string(
-          ctx, context_string.data, context_string.len) <= 0) {
-    return std::nullopt;
-  }
-  return ctx;
-#elif NCRYPTO_USE_OPENSSL_PROVIDER
-  EVP_PKEY_CTX* ctx = nullptr;
-
-  // Ed25519 requires the INSTANCE param to switch into Ed25519ctx mode.
-  // Without it, OpenSSL silently ignores the context string.
-  if (key.isA(KeyAlgorithm::ED25519)) {
-    const OSSL_PARAM params[] = {
-        OSSL_PARAM_construct_utf8_string(
-            kSignatureInstance, const_cast<char*>("Ed25519ctx"), 0),
-        OSSL_PARAM_construct_octet_string(
-            kSignatureContextString,
-            const_cast<unsigned char*>(context_string.data),
-            context_string.len),
-        OSSL_PARAM_END};
-
-    if (!EVP_DigestVerifyInit_ex(
-            ctx_.get(), &ctx, nullptr, nullptr, nullptr, key.get(), params)) {
-      return std::nullopt;
-    }
-    return ctx;
-  }
-
-  const OSSL_PARAM params[] = {
-      OSSL_PARAM_construct_octet_string(
-          kSignatureContextString,
-          const_cast<unsigned char*>(context_string.data),
-          context_string.len),
-      OSSL_PARAM_END};
+    const Buffer<const unsigned char>* context_string) {
+  return InitializeSignature<SignatureOperation::Sign>(
+      ctx_.get(), key, digest, context_string);
+}

-  if (!EVP_DigestVerifyInit_ex(
-          ctx_.get(), &ctx, nullptr, nullptr, nullptr, key.get(), params)) {
-    return std::nullopt;
-  }
-  return ctx;
-#else
-#error "Unsupported crypto backend"
-#endif
+std::optional<EVP_PKEY_CTX*> EVPMDCtxPointer::verifyInit(
+    const EVPKeyPointer& key,
+    const Digest& digest,
+    const Buffer<const unsigned char>* context_string) {
+  return InitializeSignature<SignatureOperation::Verify>(
+      ctx_.get(), key, digest, context_string);
 }

 DataPointer EVPMDCtxPointer::signOneShot(
diff --git a/deps/ncrypto/ncrypto.h b/deps/ncrypto/ncrypto.h
index 4261fc21bf1..34895ffb9c8 100644
--- a/deps/ncrypto/ncrypto.h
+++ b/deps/ncrypto/ncrypto.h
@@ -1944,19 +1944,14 @@ class EVPMDCtxPointer final {
   bool digestFinalInto(Buffer<void>* buf);
   size_t getExpectedSize();

-  std::optional<EVP_PKEY_CTX*> signInit(const EVPKeyPointer& key,
-                                        const Digest& digest);
-  std::optional<EVP_PKEY_CTX*> verifyInit(const EVPKeyPointer& key,
-                                          const Digest& digest);
-
-  std::optional<EVP_PKEY_CTX*> signInitWithContext(
+  std::optional<EVP_PKEY_CTX*> signInit(
       const EVPKeyPointer& key,
       const Digest& digest,
-      const Buffer<const unsigned char>& context_string);
-  std::optional<EVP_PKEY_CTX*> verifyInitWithContext(
+      const Buffer<const unsigned char>* context_string = nullptr);
+  std::optional<EVP_PKEY_CTX*> verifyInit(
       const EVPKeyPointer& key,
       const Digest& digest,
-      const Buffer<const unsigned char>& context_string);
+      const Buffer<const unsigned char>* context_string = nullptr);

   DataPointer signOneShot(const Buffer<const unsigned char>& buf) const;
   DataPointer sign(const Buffer<const unsigned char>& buf) const;
diff --git a/src/crypto/crypto_mac.cc b/src/crypto/crypto_mac.cc
index 85575f79142..bd06d8f9b1d 100644
--- a/src/crypto/crypto_mac.cc
+++ b/src/crypto/crypto_mac.cc
@@ -14,6 +14,7 @@

 #include <algorithm>
 #include <array>
+#include <cstring>
 #include <optional>
 #include <string>
 #include <string_view>
@@ -191,29 +192,39 @@ EVP_MAC* GetMacImplementation(Environment* env,
   return nullptr;
 }

-bool IsSettableParameter(const ncrypto::EVPMacCtxPointer& context,
-                         const char* name,
-                         unsigned int type) {
-  const OSSL_PARAM* settable = context.getSettableParams();
-  const OSSL_PARAM* descriptor =
-      settable == nullptr ? nullptr : OSSL_PARAM_locate_const(settable, name);
-  return descriptor != nullptr && descriptor->data_type == type;
-}
+enum class MacOptionType { kName, kBytes, kSize };

-bool RequireSettableParameter(Environment* env,
-                              const ncrypto::EVPMacCtxPointer& context,
-                              Local<Value> algorithm,
-                              const char* option,
-                              const char* parameter,
-                              unsigned int type) {
-  if (IsSettableParameter(context, parameter, type)) return true;
-  Utf8Value name(env->isolate(), algorithm);
-  THROW_ERR_INVALID_ARG_VALUE(
-      env,
-      "The property 'options.%s' is not supported by MAC %s",
-      option,
-      *name);
-  return false;
+struct MacOption final {
+  const char* name;
+  const char* parameter;
+  MacOptionType type;
+};
+
+constexpr std::array<MacOption, 6> kMacOptions = {{
+    {"digest", OSSL_MAC_PARAM_DIGEST, MacOptionType::kName},
+    {"cipher", OSSL_MAC_PARAM_CIPHER, MacOptionType::kName},
+    {"iv", OSSL_MAC_PARAM_IV, MacOptionType::kBytes},
+    {"customization", OSSL_MAC_PARAM_CUSTOM, MacOptionType::kBytes},
+    {"salt", OSSL_MAC_PARAM_SALT, MacOptionType::kBytes},
+    {"outputLength", OSSL_MAC_PARAM_SIZE, MacOptionType::kSize},
+}};
+
+const OSSL_PARAM* FindMacParameter(const OSSL_PARAM* settable,
+                                   const MacOption& option,
+                                   const void* data,
+                                   size_t length) {
+  if (settable == nullptr) return nullptr;
+  for (const OSSL_PARAM* param = settable; param->key != nullptr; param++) {
+    if (std::strcmp(param->key, option.parameter) != 0) continue;
+    if (option.type == MacOptionType::kSize) {
+      if (param->data_type == OSSL_PARAM_UNSIGNED_INTEGER) return param;
+    } else if (param->data_type == OSSL_PARAM_OCTET_STRING ||
+               (param->data_type == OSSL_PARAM_UTF8_STRING &&
+                std::memchr(data, 0, length) == nullptr)) {
+      return param;
+    }
+  }
+  return nullptr;
 }

 bool InitializeMacContext(Environment* env,
@@ -224,36 +235,9 @@ bool InitializeMacContext(Environment* env,
   CHECK(args[1]->IsInt32());
   CHECK(args[2]->IsObject());

-  Isolate* isolate = env->isolate();
   ByteSource key = ByteSource::FromSecretKeyBytes(env, args[3]);
-
-  std::optional<Utf8Value> digest;
-  if (!args[4]->IsUndefined()) {
-    CHECK(args[4]->IsString());
-    digest.emplace(isolate, args[4]);
-  }
-  std::optional<Utf8Value> cipher;
-  if (!args[5]->IsUndefined()) {
-    CHECK(args[5]->IsString());
-    cipher.emplace(isolate, args[5]);
-  }
-
-  const bool has_iv = !args[6]->IsUndefined();
-  ByteSource iv;
-  if (has_iv) iv = ByteSource::FromBuffer(args[6]);
-  const bool has_customization = !args[7]->IsUndefined();
-  ByteSource customization;
-  if (has_customization) customization = ByteSource::FromBuffer(args[7]);
-  const bool has_salt = !args[8]->IsUndefined();
-  ByteSource salt;
-  if (has_salt) salt = ByteSource::FromBuffer(args[8]);
-
   const bool has_output_length = !args[9]->IsUndefined();
   size_t output_length = 0;
-  if (has_output_length) {
-    CHECK(args[9]->IsUint32());
-    output_length = args[9].As<Uint32>()->Value();
-  }

   ncrypto::EVPMacPointer mac_owner;
   ncrypto::MacKind kind = ncrypto::MacKind::kOther;
@@ -269,23 +253,24 @@ bool InitializeMacContext(Environment* env,
     return false;
   }

-  if (kind == ncrypto::MacKind::kHmac && !digest.has_value()) {
+  if (kind == ncrypto::MacKind::kHmac && args[4]->IsUndefined()) {
     THROW_ERR_INVALID_ARG_VALUE(
         env, "The property 'options.digest' is required for HMAC");
     return false;
   }
-  if (kind == ncrypto::MacKind::kCmac && !cipher.has_value()) {
+  if (kind == ncrypto::MacKind::kCmac && args[5]->IsUndefined()) {
     THROW_ERR_INVALID_ARG_VALUE(
         env, "The property 'options.cipher' is required for CMAC");
     return false;
   }
   if (kind == ncrypto::MacKind::kGmac) {
-    if (!cipher.has_value()) {
+    if (args[5]->IsUndefined()) {
       THROW_ERR_INVALID_ARG_VALUE(
           env, "The property 'options.cipher' is required for GMAC");
       return false;
     }
-    if (!has_iv || iv.empty()) {
+    if (args[6]->IsUndefined() ||
+        ArrayBufferOrViewContents<unsigned char>(args[6]).empty()) {
       THROW_ERR_INVALID_ARG_VALUE(
           env, "The property 'options.iv' must be non-empty for GMAC");
       return false;
@@ -298,78 +283,85 @@ bool InitializeMacContext(Environment* env,
     return false;
   }

-  std::array<OSSL_PARAM, 7> params;
+  const OSSL_PARAM* settable = context.getSettableParams();
+  constexpr size_t kNameCount = std::count_if(
+      kMacOptions.begin(), kMacOptions.end(), [](const MacOption& option) {
+        return option.type == MacOptionType::kName;
+      });
+  std::array<std::optional<Utf8Value>, kNameCount> names;
+  size_t name_count = 0;
+  constexpr size_t kByteCount = std::count_if(
+      kMacOptions.begin(), kMacOptions.end(), [](const MacOption& option) {
+        return option.type == MacOptionType::kBytes;
+      });
+  std::optional<std::array<std::string, kByteCount>> utf8_bytes;
+  size_t utf8_count = 0;
+  std::array<OSSL_PARAM, kMacOptions.size() + 1> params;
   size_t count = 0;
-  if (digest.has_value()) {
-    if (!RequireSettableParameter(env,
-                                  context,
-                                  args[0],
-                                  "digest",
-                                  OSSL_MAC_PARAM_DIGEST,
-                                  OSSL_PARAM_UTF8_STRING)) {
-      return false;
-    }
-    params[count++] = OSSL_PARAM_construct_utf8_string(
-        OSSL_MAC_PARAM_DIGEST, const_cast<char*>(digest->out()), 0);
-  }
-  if (cipher.has_value()) {
-    if (!RequireSettableParameter(env,
-                                  context,
-                                  args[0],
-                                  "cipher",
-                                  OSSL_MAC_PARAM_CIPHER,
-                                  OSSL_PARAM_UTF8_STRING)) {
-      return false;
-    }
-    params[count++] = OSSL_PARAM_construct_utf8_string(
-        OSSL_MAC_PARAM_CIPHER, const_cast<char*>(cipher->out()), 0);
-  }
-
   unsigned char empty_parameter = 0;
-  auto add_bytes = [&](bool present,
-                       const ByteSource& value,
-                       const char* option,
-                       const char* parameter) {
-    if (!present) return true;
-    if (!RequireSettableParameter(env,
-                                  context,
-                                  args[0],
-                                  option,
-                                  parameter,
-                                  OSSL_PARAM_OCTET_STRING)) {
-      return false;
+  for (size_t i = 0; i < kMacOptions.size(); i++) {
+    Local<Value> input = args[4 + i];
+    if (input->IsUndefined()) continue;
+    const MacOption& option = kMacOptions[i];
+    const void* data = nullptr;
+    size_t length = 0;
+    switch (option.type) {
+      case MacOptionType::kName: {
+        CHECK(input->IsString());
+        auto& name = names[name_count++].emplace(env->isolate(), input);
+        data = name.out();
+        length = name.length();
+        break;
+      }
+      case MacOptionType::kBytes: {
+        // Callback arguments keep the borrowed buffer storage alive.
+        const ArrayBufferOrViewContents<unsigned char> bytes(input);
+        data = bytes.empty() ? &empty_parameter : bytes.data();
+        length = bytes.size();
+        break;
+      }
+      case MacOptionType::kSize:
+        CHECK(input->IsUint32());
+        output_length = input.As<Uint32>()->Value();
+        if (output_length > Buffer::kMaxLength) {
+          env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate()));
+          return false;
+        }
+        break;
     }
-    void* data = value.empty() ? static_cast<void*>(&empty_parameter)
-                               : const_cast<void*>(value.data());
-    params[count++] =
-        OSSL_PARAM_construct_octet_string(parameter, data, value.size());
-    return true;
-  };
-
-  if (!add_bytes(has_iv, iv, "iv", OSSL_MAC_PARAM_IV) ||
-      !add_bytes(has_customization,
-                 customization,
-                 "customization",
-                 OSSL_MAC_PARAM_CUSTOM) ||
-      !add_bytes(has_salt, salt, "salt", OSSL_MAC_PARAM_SALT)) {
-    return false;
-  }
-
-  if (has_output_length) {
-    if (output_length > Buffer::kMaxLength) {
-      env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate()));
+    const OSSL_PARAM* descriptor =
+        FindMacParameter(settable, option, data, length);
+    if (descriptor == nullptr) {
+      Utf8Value name(env->isolate(), args[0]);
+      THROW_ERR_INVALID_ARG_VALUE(
+          env,
+          "The property 'options.%s' is not supported by MAC %s",
+          option.name,
+          *name);
       return false;
     }
-    if (!RequireSettableParameter(env,
-                                  context,
-                                  args[0],
-                                  "outputLength",
-                                  OSSL_MAC_PARAM_SIZE,
-                                  OSSL_PARAM_UNSIGNED_INTEGER)) {
-      return false;
+    switch (descriptor->data_type) {
+      case OSSL_PARAM_UTF8_STRING:
+        if (option.type == MacOptionType::kBytes && length != 0) {
+          if (!utf8_bytes.has_value()) utf8_bytes.emplace();
+          std::string& bytes = (*utf8_bytes)[utf8_count++];
+          bytes.assign(static_cast<const char*>(data), length);
+          data = bytes.c_str();
+        }
+        params[count++] = OSSL_PARAM_construct_utf8_string(
+            option.parameter,
+            const_cast<char*>(static_cast<const char*>(data)),
+            length);
+        break;
+      case OSSL_PARAM_OCTET_STRING:
+        params[count++] = OSSL_PARAM_construct_octet_string(
+            option.parameter, const_cast<void*>(data), length);
+        break;
+      case OSSL_PARAM_UNSIGNED_INTEGER:
+        params[count++] =
+            OSSL_PARAM_construct_size_t(option.parameter, &output_length);
+        break;
     }
-    params[count++] =
-        OSSL_PARAM_construct_size_t(OSSL_MAC_PARAM_SIZE, &output_length);
   }
   params[count] = OSSL_PARAM_construct_end();

diff --git a/src/crypto/crypto_sig.cc b/src/crypto/crypto_sig.cc
index fbae8aeddbb..0ac52959ded 100644
--- a/src/crypto/crypto_sig.cc
+++ b/src/crypto/crypto_sig.cc
@@ -613,7 +613,6 @@ SignConfiguration::SignConfiguration(SignConfiguration&& other) noexcept
       data(std::move(other.data)),
       signature(std::move(other.signature)),
       digest(other.digest),
-      flags(other.flags),
       padding(other.padding),
       salt_length(other.salt_length),
       dsa_encoding(other.dsa_encoding),
@@ -675,12 +674,9 @@ Maybe<void> SignTraits::AdditionalConfig(
   }

   if (args[offset + 8]->IsInt32()) {  // Salt length
-    params->flags |= SignConfiguration::kHasSaltLength;
-    params->salt_length =
-        GetSaltLenFromJS(args[offset + 8]).value_or(params->salt_length);
+    params->salt_length = GetSaltLenFromJS(args[offset + 8]);
   }
   if (args[offset + 9]->IsUint32()) {  // Padding
-    params->flags |= SignConfiguration::kHasPadding;
     params->padding =
         GetPaddingFromJS(params->key.GetAsymmetricKey(), args[offset + 9]);
   }
@@ -699,7 +695,6 @@ Maybe<void> SignTraits::AdditionalConfig(
       THROW_ERR_OUT_OF_RANGE(env, "context string must be at most 255 bytes");
       return Nothing<void>();
     }
-    params->flags |= SignConfiguration::kHasContextString;
     params->context_string = IsCryptoJobAsync(mode)
                                  ? context_string.ToCopy()
                                  : context_string.ToByteSource();
@@ -732,8 +727,7 @@ bool SignTraits::DeriveBits(Environment* env,
                             CryptoErrorStore* errors) {
   const auto& key = params.key.GetAsymmetricKey();

-  bool has_context = (params.flags & SignConfiguration::kHasContextString &&
-                      params.context_string.size() > 0);
+  const bool has_context = params.context_string.size() > 0;

   if (has_context && !key.supportsContextString()) {
     errors->Insert(NodeCryptoError::CONTEXT_UNSUPPORTED);
@@ -741,40 +735,25 @@ bool SignTraits::DeriveBits(Environment* env,
     return false;
   }

-  int padding = params.padding;
-  if (!(params.flags & SignConfiguration::kHasPadding)) {
-    padding = key.getDefaultSignPadding();
-  }
-
-  std::optional<int> salt_length =
-      params.flags & SignConfiguration::kHasSaltLength
-          ? std::optional<int>(params.salt_length)
-          : std::nullopt;
+  const int padding = params.padding.has_value() ? *params.padding
+                                                 : key.getDefaultSignPadding();
+  const auto& salt_length = params.salt_length;

   auto context = EVPMDCtxPointer::New();
   if (!context) [[unlikely]]
     return false;

+  const ncrypto::Buffer<const unsigned char> context_buf{
+      .data = params.context_string.data<unsigned char>(),
+      .len = params.context_string.size(),
+  };
+  const auto* context_string = has_context ? &context_buf : nullptr;
   auto ctx = ([&] {
-    if (has_context) {
-      ncrypto::Buffer<const unsigned char> context_buf{
-          .data = params.context_string.data<unsigned char>(),
-          .len = params.context_string.size(),
-      };
-
-      switch (params.mode) {
-        case SignConfiguration::Mode::Sign:
-          return context.signInitWithContext(key, params.digest, context_buf);
-        case SignConfiguration::Mode::Verify:
-          return context.verifyInitWithContext(key, params.digest, context_buf);
-      }
-    } else {
-      switch (params.mode) {
-        case SignConfiguration::Mode::Sign:
-          return context.signInit(key, params.digest);
-        case SignConfiguration::Mode::Verify:
-          return context.verifyInit(key, params.digest);
-      }
+    switch (params.mode) {
+      case SignConfiguration::Mode::Sign:
+        return context.signInit(key, params.digest, context_string);
+      case SignConfiguration::Mode::Verify:
+        return context.verifyInit(key, params.digest, context_string);
     }
     UNREACHABLE();
   })();
diff --git a/src/crypto/crypto_sig.h b/src/crypto/crypto_sig.h
index a3d194db3f2..86f01e2afd2 100644
--- a/src/crypto/crypto_sig.h
+++ b/src/crypto/crypto_sig.h
@@ -9,6 +9,8 @@
 #include "env.h"
 #include "memory_tracker.h"

+#include <optional>
+
 namespace node {
 namespace crypto {
 static const unsigned int kNoDsaSignature = static_cast<unsigned int>(-1);
@@ -97,21 +99,13 @@ class Verify final : public SignBase {

 struct SignConfiguration final : public MemoryRetainer {
   enum class Mode { Sign, Verify };
-  enum Flags {
-    kHasNone = 0,
-    kHasSaltLength = 1,
-    kHasPadding = 2,
-    kHasContextString = 4
-  };
-
   Mode mode;
   KeyObjectData key;
   ByteSource data;
   ByteSource signature;
   ncrypto::Digest digest;
-  int flags = SignConfiguration::kHasNone;
-  int padding = 0;
-  int salt_length = 0;
+  std::optional<int> padding;
+  std::optional<int> salt_length;
   DSASigEnc dsa_encoding = DSASigEnc::DER;
   ByteSource context_string;