crypto: share digest length handling between HashInit overloads

The two Hash::HashInit() overloads duplicated the logic that
determines the digest length and validates the requested XOF output
length after the digest context is initialized. Move it into a shared
FinishHashInit() helper.

Assisted-by: Claude
Signed-off-by: James M Snell <jasnell@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/67495
Reviewed-By: Guilherme Araújo <arauujogui@gmail.com>
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>
Reviewed-By: Ethan Arrowood <ethan@arrowood.dev>
This commit is contained in:
James M Snell authored and Node.js GitHub Bot committed 2026-11-17 18:37:18 +00:00
1 parent 58fc2309f5
commit 430e4af391
2 files changed
+18 -27

No files matched your search

+13 -27
View File
@@ -711,13 +711,8 @@ void Hash::New(const FunctionCallbackInfo<Value>& args) {
}
}
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;
}
bool Hash::FinishHashInit(const EVP_MD* digest,
Maybe<unsigned int> xof_md_len) {
md_len_ = mdctx_.getDigestSize();
if (mdctx_.hasXofFlag() && !xof_md_len.IsJust() &&
ShouldRejectMissingXofLength(digest, md_len_)) {
@@ -740,6 +735,16 @@ bool Hash::HashInit(const EVP_MD* digest, Maybe<unsigned int> xof_md_len) {
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) {
@@ -749,26 +754,7 @@ bool Hash::HashInit(const EVP_MD* digest,
return false;
}
md_len_ = mdctx_.getDigestSize();
if (mdctx_.hasXofFlag() && !xof_md_len.IsJust() &&
ShouldRejectMissingXofLength(digest, md_len_)) {
MarkInvalidXofLength();
mdctx_.reset();
return false;
}
if (xof_md_len.IsJust() && xof_md_len.FromJust() != md_len_) {
// This is a little hack to cause createHash to fail when an incorrect
// hashSize option was passed for a non-XOF hash function.
if (!mdctx_.hasXofFlag()) [[unlikely]] {
MarkInvalidXofLength();
mdctx_.reset();
return false;
}
md_len_ = xof_md_len.FromJust();
}
return true;
return FinishHashInit(digest, xof_md_len);
}
bool Hash::HashUpdate(const char* data, size_t len) {
+5
View File
@@ -57,6 +57,11 @@ 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_;