crypto: discover hashes from OpenSSL providers

Enumerate usable digests and aliases from activated OpenSSL 3 providers
rather than relying only on the legacy digest registry. Normalize
provider aliases, omit numeric OIDs and NULL, and validate them against
the active default property query. Preserve legacy names and the OpenSSL
1.1.1 and BoringSSL paths.

Expose KECCAK-KMAC-128, KECCAK-256, SHA256-192, and other provider
digests. Add `functionName` and `customization` options for cSHAKE
digests in `createHash()` and `crypto.hash()` with OpenSSL 4.0 or later.

Resolve provider-only digest names across hashing, HMAC, KDF, signing,
verification, and RSA digest options. Keep ordinary hash construction
and one-shot hashing on the original binding arities and direct
initialization paths. Use parameterized setup only when cSHAKE options
are supplied.

Lazily cache successful provider fetches per Environment.
Index entries by case-insensitive query, canonical, and alias names.
Deduplicate owners by provider and canonical identity. Return borrowed
pointers on warm hits.

Introduce a process-wide FIPS-state generation that advances only after
successful, state-changing `setFips()` calls. Use it to invalidate
per-Environment digest caches and refresh `getHashes()` snapshots in the
main thread and workers. Keep cache IDs monotonic across invalidation
because JavaScript Realms can retain them. Existing hash contexts can
finish across a transition.

Release provider owners before unloading worker addon DSOs. Document
provider-dependent availability and operation-specific restrictions.
Add known-answer vectors, option validation, provider resolution,
property-query, FIPS transition, worker, snapshot, and cross-API
coverage.

Refs: https://github.com/nodejs/node/issues/62982
Signed-off-by: Filip Skokan <panva.ip@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/65484
Backport-PR-URL: https://github.com/nodejs/node/pull/65596
Fixes: https://github.com/nodejs/node/issues/43040
Fixes: https://github.com/nodejs/node/issues/64866
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
This commit is contained in:
Filip Skokan authored and Antoine du Hamel committed 2026-09-15 10:49:05 +02:00
1 parent 5e95f4f6ac
commit 7c7e95a3bd
19 files changed
+1956 -183

No files matched your search

+221 -8
View File
@@ -14,6 +14,7 @@
#endif
#include <algorithm>
#include <array>
#include <atomic>
#include <climits>
#include <cstring>
#include <string_view>
@@ -507,23 +508,43 @@ DataPointer DataPointer::resize(size_t len) {
}
// ============================================================================
bool isFipsEnabled() {
ClearErrorOnReturn clear_error_on_return;
namespace {
// This generation only coordinates cache invalidation. It does not make
// OpenSSL default property changes safe to race with crypto operations.
std::atomic<uint64_t> fips_state_generation{0};
bool isFipsEnabledRaw() {
#if OPENSSL_VERSION_MAJOR >= 3
return EVP_default_properties_is_fips_enabled(nullptr) == 1;
#else
return FIPS_mode() == 1;
#endif
}
} // namespace
bool isFipsEnabled() {
ClearErrorOnReturn clear_error_on_return;
return isFipsEnabledRaw();
}
bool setFipsEnabled(bool enable, CryptoErrorList* errors) {
if (isFipsEnabled() == enable) return true;
const bool was_enabled = isFipsEnabled();
if (was_enabled == enable) return true;
ClearErrorOnReturn clearErrorOnReturn(errors);
#if OPENSSL_VERSION_MAJOR >= 3
return EVP_default_properties_enable_fips(nullptr, enable ? 1 : 0) == 1;
const bool success =
EVP_default_properties_enable_fips(nullptr, enable ? 1 : 0) == 1;
#else
return FIPS_mode_set(enable ? 1 : 0) == 1;
const bool success = FIPS_mode_set(enable ? 1 : 0) == 1;
#endif
if (isFipsEnabledRaw() != was_enabled) {
fips_state_generation.fetch_add(1, std::memory_order_release);
}
return success;
}
uint64_t getFipsStateGeneration() {
return fips_state_generation.load(std::memory_order_acquire);
}
bool testFipsEnabled() {
@@ -4406,11 +4427,120 @@ bool SSLCtxPointer::setCipherSuites(const char* ciphers) {
// ============================================================================
namespace {
constexpr char AsciiToLower(char c) {
return c >= 'A' && c <= 'Z' ? c + ('a' - 'A') : c;
}
#if NCRYPTO_USE_OPENSSL3_PROVIDER
void PushAlgorithmAlias(const char* name, void* arg) {
if (name == nullptr) return;
static_cast<std::vector<std::string>*>(arg)->emplace_back(name);
}
#endif
} // namespace
#if OPENSSL_WITH_AES_SIV || OPENSSL_WITH_AES_GCM_SIV
Cipher::Cipher(DeleteFnPtr<EVP_CIPHER, EVP_CIPHER_free> cipher)
: cipher_(cipher.get()), fetched_cipher_(std::move(cipher)) {}
#endif
size_t CaseInsensitiveNameHash::operator()(
std::string_view name) const noexcept {
size_t hash = 5381;
for (char c : name) hash = ((hash << 5) + hash) ^ AsciiToLower(c);
return hash;
}
bool CaseInsensitiveNameEqual::operator()(std::string_view lhs,
std::string_view rhs) const noexcept {
if (lhs.size() != rhs.size()) return false;
for (size_t n = 0; n < lhs.size(); n++) {
if (AsciiToLower(lhs[n]) != AsciiToLower(rhs[n])) return false;
}
return true;
}
DigestCache::Result DigestCache::lookup(const char* name,
uint64_t generation) const {
#if NCRYPTO_USE_OPENSSL3_PROVIDER
if (generation_ != generation) return {};
const auto it = aliases_.find(name);
if (it == aliases_.end()) return {};
return lookup(it->second, generation);
#else
static_cast<void>(name);
static_cast<void>(generation);
return {};
#endif
}
DigestCache::Result DigestCache::insert(const char* name,
const EVP_MD* digest,
uint64_t generation) {
#if NCRYPTO_USE_OPENSSL3_PROVIDER
if (generation_ != generation || name == nullptr || digest == nullptr) {
return {};
}
const char* canonical_name = EVP_MD_get0_name(digest);
const OSSL_PROVIDER* provider = EVP_MD_get0_provider(digest);
if (canonical_name == nullptr || provider == nullptr) return {};
for (size_t index = 0; index < digests_.size(); index++) {
const EVP_MD* cached = digests_[index].get();
if (cached == nullptr) continue;
const char* cached_name = EVP_MD_get0_name(cached);
if (EVP_MD_get0_provider(cached) == provider && cached_name != nullptr &&
CaseInsensitiveNameEqual()(cached_name, canonical_name)) {
const int32_t id = static_cast<int32_t>(first_id_ + index);
aliases_.insert_or_assign(name, id);
return {cached, id};
}
}
if (next_id_ == UINT32_MAX ||
EVP_MD_up_ref(const_cast<EVP_MD*>(digest)) != 1) {
return {};
}
digests_.emplace_back(const_cast<EVP_MD*>(digest));
const int32_t id = static_cast<int32_t>(next_id_++);
const size_t index = digests_.size() - 1;
std::vector<std::string> aliases;
EVP_MD_names_do_all(digests_[index].get(), PushAlgorithmAlias, &aliases);
for (const std::string& alias : aliases) aliases_.emplace(alias, id);
aliases_.insert_or_assign(name, id);
return {digests_[index].get(), id};
#else
static_cast<void>(name);
static_cast<void>(digest);
static_cast<void>(generation);
return {};
#endif
}
void DigestCache::reset(uint64_t generation) {
#if NCRYPTO_USE_OPENSSL3_PROVIDER
if (generation_ == generation) return;
aliases_.clear();
digests_.clear();
first_id_ = next_id_;
#endif
generation_ = generation;
}
const DigestCache::AliasMap& DigestCache::aliases() const {
#if NCRYPTO_USE_OPENSSL3_PROVIDER
return aliases_;
#else
static const AliasMap empty;
return empty;
#endif
}
Cipher::Cipher(const Cipher& other) : cipher_(other.cipher_) {
#if OPENSSL_WITH_AES_SIV || OPENSSL_WITH_AES_GCM_SIV
if (other.fetched_cipher_ != nullptr) {
@@ -6479,11 +6609,19 @@ EVP_MD_CTX* EVPMDCtxPointer::release() {
return ctx_.release();
}
bool EVPMDCtxPointer::digestInit(const Digest& digest) {
bool EVPMDCtxPointer::digestInit(const EVP_MD* digest) {
if (!ctx_) return false;
return EVP_DigestInit_ex(ctx_.get(), digest, nullptr) > 0;
}
#if !defined(OPENSSL_IS_BORINGSSL) && OPENSSL_VERSION_PREREQ(4, 0)
bool EVPMDCtxPointer::digestInit(const EVP_MD* digest,
const OSSL_PARAM* params) {
if (!ctx_) return false;
return EVP_DigestInit_ex2(ctx_.get(), digest, params) > 0;
}
#endif
bool EVPMDCtxPointer::digestUpdate(const Buffer<const void>& in) {
if (!ctx_) return false;
return EVP_DigestUpdate(ctx_.get(), in.data, in.len) > 0;
@@ -7009,7 +7147,10 @@ DataPointer xofHashDigest(const Buffer<const unsigned char>& buf,
if (ctx.digestInit(md) != 1) {
return {};
}
if (ctx.digestUpdate(reinterpret_cast<const Buffer<const void>&>(buf)) != 1) {
if (ctx.digestUpdate(Buffer<const void>{
.data = buf.data,
.len = buf.len,
}) != 1) {
return {};
}
return ctx.digestFinal(output_length);
@@ -7145,14 +7286,86 @@ size_t Digest::size() const {
return EVP_MD_size(md_);
}
#if NCRYPTO_USE_OPENSSL3_PROVIDER
Digest::Digest(DeleteFnPtr<EVP_MD, EVP_MD_free> md)
: md_(md.get()), fetched_md_(std::move(md)) {}
#endif
Digest::Digest(const Digest& other) : md_(other.md_) {
#if NCRYPTO_USE_OPENSSL3_PROVIDER
if (other.fetched_md_ != nullptr) {
if (EVP_MD_up_ref(other.fetched_md_.get()) == 1) {
fetched_md_.reset(other.fetched_md_.get());
} else {
md_ = nullptr;
}
}
#endif
}
Digest& Digest::operator=(const Digest& other) {
if (this == &other) return *this;
#if NCRYPTO_USE_OPENSSL3_PROVIDER
if (other.fetched_md_ != nullptr) {
if (EVP_MD_up_ref(other.fetched_md_.get()) == 1) {
fetched_md_.reset(other.fetched_md_.get());
} else {
fetched_md_.reset();
md_ = nullptr;
return *this;
}
} else {
fetched_md_.reset();
}
#endif
md_ = other.md_;
return *this;
}
const Digest Digest::MD5 = Digest(EVP_md5());
const Digest Digest::SHA1 = Digest(EVP_sha1());
const Digest Digest::SHA256 = Digest(EVP_sha256());
const Digest Digest::SHA384 = Digest(EVP_sha384());
const Digest Digest::SHA512 = Digest(EVP_sha512());
#if NCRYPTO_USE_OPENSSL3_PROVIDER
namespace {
bool IsSupportedDigest(const EVP_MD* md) {
if (md == nullptr || EVP_MD_is_a(md, "NULL")) return false;
// OpenSSL currently crashes when ML-DSA-MU finalizes an empty input. Keep it
// unavailable until the provider implementation is fixed.
// https://github.com/openssl/openssl/issues/32445
if (EVP_MD_is_a(md, "ML-DSA-MU")) return false;
return true;
}
} // namespace
#endif
const Digest Digest::FromName(const char* name) {
return ncrypto::getDigestByName(name);
const EVP_MD* md = ncrypto::getDigestByName(name);
if (md != nullptr) {
#if NCRYPTO_USE_OPENSSL3_PROVIDER
if (md == EVP_md_null()) return Digest();
#endif
return Digest(md);
}
return Fetch(name);
}
const Digest Digest::Fetch(const char* name) {
#if NCRYPTO_USE_OPENSSL3_PROVIDER
MarkPopErrorOnReturn mark_pop_error_on_return;
DeleteFnPtr<EVP_MD, EVP_MD_free> fetched(
EVP_MD_fetch(nullptr, name, nullptr));
if (IsSupportedDigest(fetched.get())) {
return Digest(std::move(fetched));
}
#endif
return Digest();
}
// ============================================================================
+81 -3
View File
@@ -13,6 +13,7 @@
#include <openssl/ssl.h>
#include <openssl/x509.h>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <list>
#include <memory>
@@ -397,9 +398,12 @@ class Digest final {
static constexpr size_t MAX_SIZE = EVP_MAX_MD_SIZE;
Digest() = default;
Digest(const EVP_MD* md) : md_(md) {}
Digest(const Digest&) = default;
Digest& operator=(const Digest&) = default;
Digest(const Digest& other);
Digest& operator=(const Digest& other);
inline Digest& operator=(const EVP_MD* md) {
#if NCRYPTO_USE_OPENSSL3_PROVIDER
fetched_md_.reset();
#endif
md_ = md;
return *this;
}
@@ -418,9 +422,72 @@ class Digest final {
static const Digest SHA512;
static const Digest FromName(const char* name);
static const Digest Fetch(const char* name);
private:
const EVP_MD* md_ = nullptr;
#if NCRYPTO_USE_OPENSSL3_PROVIDER
explicit Digest(DeleteFnPtr<EVP_MD, EVP_MD_free> md);
DeleteFnPtr<EVP_MD, EVP_MD_free> fetched_md_;
#endif
};
struct CaseInsensitiveNameHash {
using is_transparent = void;
size_t operator()(std::string_view name) const noexcept;
};
struct CaseInsensitiveNameEqual {
using is_transparent = void;
bool operator()(std::string_view lhs, std::string_view rhs) const noexcept;
};
class DigestCache final {
public:
struct Result {
const EVP_MD* digest = nullptr;
int32_t id = -1;
};
using AliasMap = std::unordered_map<std::string,
int32_t,
CaseInsensitiveNameHash,
CaseInsensitiveNameEqual>;
DigestCache() = default;
NCRYPTO_DISALLOW_COPY_AND_MOVE(DigestCache)
Result lookup(const char* name, uint64_t generation) const;
inline Result lookup(int32_t id, uint64_t generation) const {
#if NCRYPTO_USE_OPENSSL3_PROVIDER
if (generation_ != generation || id == -1) return {};
const uint32_t unsigned_id = static_cast<uint32_t>(id);
if (unsigned_id < first_id_) return {};
const size_t index = unsigned_id - first_id_;
if (index >= digests_.size()) return {};
return {digests_[index].get(), id};
#else
static_cast<void>(id);
static_cast<void>(generation);
return {};
#endif
}
Result insert(const char* name, const EVP_MD* digest, uint64_t generation);
void reset(uint64_t generation);
const AliasMap& aliases() const;
private:
uint64_t generation_ = 0;
#if NCRYPTO_USE_OPENSSL3_PROVIDER
using EVPMDPointer = DeleteFnPtr<EVP_MD, EVP_MD_free>;
// IDs are not reused across generations because JavaScript caches them
// independently in each Realm.
uint32_t first_id_ = 0;
uint32_t next_id_ = 0;
std::vector<EVPMDPointer> digests_;
AliasMap aliases_;
#endif
};
// Computes a fixed-length digest.
@@ -1690,7 +1757,16 @@ class EVPMDCtxPointer final {
void reset(EVP_MD_CTX* ctx = nullptr);
EVP_MD_CTX* release();
bool digestInit(const Digest& digest);
bool digestInit(const EVP_MD* digest);
inline bool digestInit(const Digest& digest) {
return digestInit(digest.get());
}
#if !defined(OPENSSL_IS_BORINGSSL) && OPENSSL_VERSION_PREREQ(4, 0)
bool digestInit(const EVP_MD* digest, const OSSL_PARAM* params);
inline bool digestInit(const Digest& digest, const OSSL_PARAM* params) {
return digestInit(digest.get(), params);
}
#endif
bool digestUpdate(const Buffer<const void>& in);
DataPointer digestFinal(size_t length);
bool digestFinalInto(Buffer<void>* buf);
@@ -1880,6 +1956,8 @@ bool isFipsEnabled();
bool setFipsEnabled(bool enabled, CryptoErrorList* errors);
uint64_t getFipsStateGeneration();
bool testFipsEnabled();
// ============================================================================
+122 -20
View File
@@ -3789,6 +3789,11 @@ and description of each available elliptic curve.
<!-- YAML
added: v0.1.92
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/65484
description: Hash algorithms exposed by OpenSSL providers are now
supported. The `functionName` and `customization` options
were added for cSHAKE hash functions.
- version: v12.8.0
pr-url: https://github.com/nodejs/node/pull/28805
description: The `outputLength` option was added for XOF hash functions.
@@ -3796,6 +3801,14 @@ changes:
* `algorithm` {string}
* `options` {Object} [`stream.transform` options][]
* `customization` {string|ArrayBuffer|Buffer|TypedArray|DataView} For cSHAKE
hash functions, specifies the customization byte string. **Default:** an
empty byte string.
* `functionName` {string|ArrayBuffer|Buffer|TypedArray|DataView} For cSHAKE
hash functions, specifies the NIST function-name byte string. **Default:**
an empty byte string.
* `outputLength` {number} For XOF hash functions, specifies the desired
output length in bytes.
* Returns: {Hash}
Creates and returns a `Hash` object that can be used to generate hash digests
@@ -3803,12 +3816,23 @@ using the given `algorithm`. Optional `options` argument controls stream
behavior. For XOF hash functions such as `'shake256'`, the `outputLength` option
can be used to specify the desired output length in bytes.
The `functionName` and `customization` options apply only to cSHAKE-128 and
cSHAKE-256. They are supported only when Node.js is built with OpenSSL 4.0 or
later and the selected provider supports the corresponding digest parameters.
Strings are encoded as UTF-8, and neither strings nor byte values may contain
NUL bytes. Both options default to an empty byte string. For OpenSSL's built-in
providers, `functionName` is case-sensitive and must be `''`, `'TupleHash'`,
`'ParallelHash'`, or `'KMAC'`. Other providers can impose different
restrictions. With both options empty, cSHAKE produces the same output as the
corresponding SHAKE function for the same output length. `cshake-128` and
`cshake-256` default to output lengths of 32 and 64 bytes, respectively.
When the data is small (< 5MB) and readily available, [`crypto.hash()`][] is usually faster.
The `algorithm` is dependent on the available algorithms supported by the
version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc.
On recent releases of OpenSSL, `openssl list -digest-algorithms` will
display the available digest algorithms.
The available algorithms depend on the version and configuration of OpenSSL on
the platform. Examples are `'sha256'` and `'sha512'`. Use
[`crypto.getHashes()`][] to obtain the list of hash algorithms available to the
Node.js process.
Example: generating the sha256 sum of a file
@@ -3891,10 +3915,11 @@ changes:
Creates and returns an `Hmac` object that uses the given `algorithm` and `key`.
Optional `options` argument controls stream behavior.
The `algorithm` is dependent on the available algorithms supported by the
version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc.
On recent releases of OpenSSL, `openssl list -digest-algorithms` will
display the available digest algorithms.
The available algorithms depend on the version and configuration of OpenSSL on
the platform. Examples are `'sha256'` and `'sha512'`.
[`crypto.getHashes()`][] lists algorithms available to the hashing APIs, but
HMAC imposes additional restrictions, so not every listed algorithm is
suitable.
The `key` is the HMAC key used to generate the cryptographic HMAC hash. If it is
a [`KeyObject`][], its type must be `secret`. If it is a string, please consider
@@ -4171,8 +4196,10 @@ added: v0.1.92
* Returns: {Sign}
Creates and returns a `Sign` object that uses the given `algorithm`. Use
[`crypto.getHashes()`][] to obtain the names of the available digest algorithms.
Optional `options` argument controls the `stream.Writable` behavior.
[`crypto.getHashes()`][] to obtain the names available to the hashing APIs. The
key type and signature scheme can impose additional restrictions on which
digests can be used. Optional `options` argument controls the
`stream.Writable` behavior.
In some cases, a `Sign` instance can be created using the name of a signature
algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use
@@ -4191,8 +4218,9 @@ added: v0.1.92
* Returns: {Verify}
Creates and returns a `Verify` object that uses the given algorithm.
Use [`crypto.getHashes()`][] to obtain an array of names of the available
signing algorithms. Optional `options` argument controls the
Use [`crypto.getHashes()`][] to obtain the names available to the hashing APIs.
The key type and signature scheme can impose additional restrictions on which
digests can be used. Optional `options` argument controls the
`stream.Writable` behavior.
In some cases, a `Verify` instance can be created using the name of a signature
@@ -4439,6 +4467,10 @@ changes:
Generates a new asymmetric key pair of the given `type`. See the
supported [asymmetric key types][].
For RSA-PSS keys, [`crypto.getHashes()`][] lists algorithms available to the
hashing APIs, but not every listed digest can be encoded in RSA-PSS parameters
or is supported by the active RSA implementation.
If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function
behaves as if [`keyObject.export()`][] had been called on its result. Otherwise,
the respective part of the key is returned as a [`KeyObject`][].
@@ -4561,6 +4593,10 @@ changes:
Generates a new asymmetric key pair of the given `type`. See the
supported [asymmetric key types][].
For RSA-PSS keys, [`crypto.getHashes()`][] lists algorithms available to the
hashing APIs, but not every listed digest can be encoded in RSA-PSS parameters
or is supported by the active RSA implementation.
If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function
behaves as if [`keyObject.export()`][] had been called on its result. Otherwise,
the respective part of the key is returned as a [`KeyObject`][].
@@ -4919,11 +4955,27 @@ mode][].
<!-- YAML
added: v0.9.3
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/65484
description: Names and aliases exposed by loaded OpenSSL providers that
match the default property query are now included.
-->
* Returns: {string\[]} An array of the names of the supported hash algorithms,
such as `'RSA-SHA256'`. Hash algorithms are also called "digest" algorithms.
This is the authoritative Node.js list of hash algorithms available to
[`crypto.createHash()`][] and [`crypto.hash()`][] in the current process. With
OpenSSL 3 or later, the list depends on the loaded providers and the default
property query in effect when the list is first generated. Some listed
algorithms can require API-specific options, such as `outputLength` for XOF
hash functions.
A listed hash algorithm is not necessarily supported by APIs that combine a
digest with another cryptographic operation, such as HMAC, key derivation, or
signing. Those operations can apply additional restrictions.
```mjs
const {
getHashes,
@@ -4960,6 +5012,11 @@ added:
- v21.7.0
- v20.12.0
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/65484
description: Hash algorithms exposed by OpenSSL providers are now
supported. The `functionName` and `customization` options
were added for cSHAKE hash functions.
- version:
- v25.5.0
- v24.13.1
@@ -4977,6 +5034,12 @@ changes:
into a `TypedArray` using either `TextEncoder` or `Buffer.from()` and passing
the encoded `TypedArray` into this API instead.
* `options` {Object|string}
* `customization` {string|ArrayBuffer|Buffer|TypedArray|DataView} For cSHAKE
hash functions, specifies the customization byte string. **Default:** an
empty byte string.
* `functionName` {string|ArrayBuffer|Buffer|TypedArray|DataView} For cSHAKE
hash functions, specifies the NIST function-name byte string. **Default:**
an empty byte string.
* `outputEncoding` {string} [Encoding][encoding] used to encode the
returned digest. **Default:** `'hex'`.
* `outputLength` {number} For XOF hash functions such as 'shake256',
@@ -4988,10 +5051,21 @@ the object-based `crypto.createHash()` when hashing a smaller amount of data
(<= 5MB) that's readily available. If the data can be big or if it is streamed,
it's still recommended to use `crypto.createHash()` instead.
The `algorithm` is dependent on the available algorithms supported by the
version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc.
On recent releases of OpenSSL, `openssl list -digest-algorithms` will
display the available digest algorithms.
The available algorithms depend on the version and configuration of OpenSSL on
the platform. Examples are `'sha256'` and `'sha512'`. Use
[`crypto.getHashes()`][] to obtain the list of hash algorithms available to the
Node.js process.
The `functionName` and `customization` options apply only to cSHAKE-128 and
cSHAKE-256. They are supported only when Node.js is built with OpenSSL 4.0 or
later and the selected provider supports the corresponding digest parameters.
Strings are encoded as UTF-8, and neither strings nor byte values may contain
NUL bytes. Both options default to an empty byte string. For OpenSSL's built-in
providers, `functionName` is case-sensitive and must be `''`, `'TupleHash'`,
`'ParallelHash'`, or `'KMAC'`. Other providers can impose different
restrictions. With both options empty, cSHAKE produces the same output as the
corresponding SHAKE function for the same output length. `cshake-128` and
`cshake-256` default to output lengths of 32 and 64 bytes, respectively.
If `options` is a string, then it specifies the `outputEncoding`.
@@ -5063,6 +5137,10 @@ changes:
HKDF is a simple key derivation function defined in RFC 5869. The given `ikm`,
`salt` and `info` are used with the `digest` to derive a key of `keylen` bytes.
The available digest algorithms depend on the version and configuration of
OpenSSL. HKDF uses HMAC internally. [`crypto.getHashes()`][] lists algorithms
available to the hashing APIs, but not every listed algorithm is necessarily
suitable for HMAC or HKDF.
The supplied `callback` function is called with two arguments: `err` and
`derivedKey`. If an error occurs while deriving the key, `err` will be set;
@@ -5122,6 +5200,10 @@ changes:
Provides a synchronous HKDF key derivation function as defined in RFC 5869. The
given `ikm`, `salt` and `info` are used with the `digest` to derive a key of
`keylen` bytes.
The available digest algorithms depend on the version and configuration of
OpenSSL. HKDF uses HMAC internally. [`crypto.getHashes()`][] lists algorithms
available to the hashing APIs, but not every listed algorithm is necessarily
suitable for HMAC or HKDF.
The successfully generated `derivedKey` will be returned as an {ArrayBuffer}.
@@ -5231,8 +5313,10 @@ pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => {
});
```
An array of supported digest functions can be retrieved using
[`crypto.getHashes()`][].
The available digest algorithms depend on the version and configuration of
OpenSSL. PBKDF2 uses HMAC internally. [`crypto.getHashes()`][] lists algorithms
available to the hashing APIs, but not every listed algorithm is necessarily
suitable for HMAC or PBKDF2.
This API uses libuv's threadpool, which can have surprising and
negative performance implications for some applications; see the
@@ -5304,8 +5388,10 @@ const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512');
console.log(key.toString('hex')); // '3745e48...08d59ae'
```
An array of supported digest functions can be retrieved using
[`crypto.getHashes()`][].
The available digest algorithms depend on the version and configuration of
OpenSSL. PBKDF2 uses HMAC internally. [`crypto.getHashes()`][] lists algorithms
available to the hashing APIs, but not every listed algorithm is necessarily
suitable for HMAC or PBKDF2.
### `crypto.privateDecrypt(privateKey, buffer)`
@@ -5361,6 +5447,10 @@ changes:
Decrypts `buffer` with `privateKey`. `buffer` was previously encrypted using
the corresponding public key, for example using [`crypto.publicEncrypt()`][].
[`crypto.getHashes()`][] lists algorithms available to the hashing APIs, but
the active RSA implementation can impose additional restrictions on digests
used for OAEP or MGF1.
If `privateKey` is not a [`KeyObject`][], this function behaves as if
`privateKey` had been passed to [`crypto.createPrivateKey()`][]. If it is an
object, the `padding` property can be passed. Otherwise, this function uses
@@ -5509,6 +5599,10 @@ Encrypts the content of `buffer` with `key` and returns a new
[`Buffer`][] with encrypted content. The returned data can be decrypted using
the corresponding private key, for example using [`crypto.privateDecrypt()`][].
[`crypto.getHashes()`][] lists algorithms available to the hashing APIs, but
the active RSA implementation can impose additional restrictions on digests
used for OAEP or MGF1.
If `key` is not a [`KeyObject`][], this function behaves as if
`key` had been passed to [`crypto.createPublicKey()`][]. If it is an
object, the `padding` property can be passed. Otherwise, this function uses
@@ -6285,6 +6379,10 @@ dependent upon the key type.
`algorithm` is required to be `null` or `undefined` for Ed25519, Ed448, and
ML-DSA.
[`crypto.getHashes()`][] lists algorithms available to the hashing APIs, but
the key type and signature scheme determine whether a listed digest can be
used for signing.
If `key` is not a [`KeyObject`][], this function behaves as if `key` had been
passed to [`crypto.createPrivateKey()`][]. When `key` is a string, `ArrayBuffer`,
[`Buffer`][], `TypedArray`, or `DataView`, it must contain PEM-encoded key
@@ -6422,6 +6520,10 @@ key type.
`algorithm` is required to be `null` or `undefined` for Ed25519, Ed448, and
ML-DSA.
[`crypto.getHashes()`][] lists algorithms available to the hashing APIs, but
the key type and signature scheme determine whether a listed digest can be
used for verification.
If `key` is not a [`KeyObject`][], this function behaves as if `key` had been
passed to [`crypto.createPublicKey()`][]. When `key` is a string, `ArrayBuffer`,
[`Buffer`][], `TypedArray`, or `DataView`, it must contain PEM-encoded key
+64 -2
View File
@@ -7,6 +7,7 @@ const {
StringPrototypeToLowerCase,
Symbol,
TypedArrayPrototypeGetBuffer,
TypedArrayPrototypeIncludes,
} = primordials;
const {
@@ -31,6 +32,8 @@ const {
kHandle,
getCachedHashId,
getHashCache,
getArrayBufferOrView,
getBufferSourceBytes,
getOptionalByteLength,
} = require('internal/crypto/util');
@@ -93,6 +96,17 @@ const maybeEmitDeprecationWarning = getDeprecationWarningEmitter(
},
);
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(algorithm, options) {
if (!new.target)
return new Hash(algorithm, options);
@@ -106,10 +120,36 @@ function Hash(algorithm, options) {
// Coerce -0 to +0.
xofLen += 0;
}
let functionName;
let customization;
if (!isCopy && options !== undefined && options !== null) {
const functionNameOption = options.functionName;
if (functionNameOption !== undefined) {
functionName = normalizeCShakeParameter(
functionNameOption, 'options.functionName');
}
const customizationOption = options.customization;
if (customizationOption !== undefined) {
customization = normalizeCShakeParameter(
customizationOption, 'options.customization');
}
}
// Lookup the cached ID from JS land because it's faster than decoding
// the string in C++ land.
const algorithmId = isCopy ? -1 : getCachedHashId(algorithm);
this[kHandle] = new _Hash(algorithm, xofLen, algorithmId, getHashCache());
if (functionName === undefined && customization === undefined) {
this[kHandle] = new _Hash(
algorithm, xofLen, algorithmId, getHashCache());
} else {
this[kHandle] = new _Hash(
algorithm,
xofLen,
algorithmId,
getHashCache(),
functionName,
customization,
);
}
this[kState] = {
[kFinalized]: false,
};
@@ -294,8 +334,15 @@ function hash(algorithm, input, options) {
if (typeof input !== 'string' && !isArrayBufferView(input)) {
throw new ERR_INVALID_ARG_TYPE('input', ['Buffer', 'TypedArray', 'DataView', 'string'], input);
}
if (options === undefined) {
maybeEmitDeprecationWarning(algorithm);
return oneShotDigest(algorithm, getCachedHashId(algorithm), getHashCache(),
input, 'hex', encodingsMap.hex, undefined);
}
let outputEncoding;
let outputLength;
let functionName;
let customization;
if (typeof options === 'string') {
outputEncoding = options;
@@ -303,6 +350,16 @@ function hash(algorithm, input, options) {
validateObject(options, 'options');
outputLength = options.outputLength;
outputEncoding = options.outputEncoding;
const functionNameOption = options.functionName;
if (functionNameOption !== undefined) {
functionName = normalizeCShakeParameter(
functionNameOption, 'options.functionName');
}
const customizationOption = options.customization;
if (customizationOption !== undefined) {
customization = normalizeCShakeParameter(
customizationOption, 'options.customization');
}
}
outputEncoding ??= 'hex';
@@ -333,8 +390,13 @@ function hash(algorithm, input, options) {
maybeEmitDeprecationWarning(algorithm);
}
if (functionName === undefined && customization === undefined) {
return oneShotDigest(algorithm, getCachedHashId(algorithm), getHashCache(),
input, normalized, encodingsMap[normalized], outputLength);
}
return oneShotDigest(algorithm, getCachedHashId(algorithm), getHashCache(),
input, normalized, encodingsMap[normalized], outputLength);
input, normalized, encodingsMap[normalized], outputLength,
functionName, customization);
}
module.exports = {
+42 -7
View File
@@ -5,6 +5,7 @@ const {
ArrayBufferPrototypeGetByteLength,
ArrayPrototypeIncludes,
ArrayPrototypePush,
ArrayPrototypeSlice,
BigInt,
DataViewPrototypeGetBuffer,
DataViewPrototypeGetByteLength,
@@ -48,6 +49,7 @@ const {
kKeyVariantAES_OCB_128: hasAesOcbMode,
Argon2Job,
getFipsCrypto,
getFipsCryptoGeneration,
KmacJob,
} = internalBinding('crypto');
@@ -117,24 +119,57 @@ function toBuf(val, encoding) {
}
let _hashCache;
if (isBuildingSnapshot()) {
addSerializeCallback(() => { _hashCache = undefined; });
}
function getHashCache() {
if (_hashCache === undefined) {
_hashCache = getCachedAliases();
if (isBuildingSnapshot()) {
// For dynamic linking, clear the map.
addSerializeCallback(() => { _hashCache = undefined; });
}
while (_hashCache === undefined) {
const generation = getFipsCryptoGeneration();
const cache = getCachedAliases();
if (generation !== getFipsCryptoGeneration()) continue;
_hashCache = cache;
}
return _hashCache;
}
function cachedArrayByFipsGeneration(fn, onRefresh) {
let result;
let generation;
if (isBuildingSnapshot()) {
addSerializeCallback(() => {
result = undefined;
generation = undefined;
});
}
return () => {
while (true) {
const current = getFipsCryptoGeneration();
if (result === undefined || generation !== current) {
const next = fn();
if (current !== getFipsCryptoGeneration()) continue;
result = next;
generation = current;
if (onRefresh !== undefined) onRefresh();
}
return ArrayPrototypeSlice(result);
}
};
}
function getCachedHashId(algorithm) {
const result = getHashCache()[algorithm];
return result === undefined ? -1 : result;
}
const getCiphers = cachedResult(() => filterDuplicateStrings(_getCiphers()));
const getHashes = cachedResult(() => filterDuplicateStrings(_getHashes()));
const getHashes = cachedArrayByFipsGeneration(
() => filterDuplicateStrings(_getHashes()),
() => {
_hashCache = undefined;
});
const getCurves = cachedResult(() => filterDuplicateStrings(_getCurves()));
function setEngine(id, flags) {
+391 -126
View File
@@ -79,59 +79,100 @@ constexpr BoringSSLDigest kBoringSSLDigests[] = {
};
#endif
#if OPENSSL_VERSION_MAJOR >= 3
void PushAliases(const char* name, void* data) {
static_cast<std::vector<std::string>*>(data)->push_back(name);
void ResetHashCache(Environment* env,
uint64_t generation,
Local<Object> algorithm_cache = Local<Object>()) {
#if NCRYPTO_USE_OPENSSL3_PROVIDER
ncrypto::DigestCache* cache = env->provider_digest_cache.get();
CHECK_NOT_NULL(cache);
if (!algorithm_cache.IsEmpty()) {
Isolate* isolate = env->isolate();
Local<Context> context = isolate->GetCurrentContext();
for (const auto& entry : cache->aliases()) {
if (algorithm_cache
->Set(context,
OneByteString(isolate, entry.first),
Int32::New(isolate, -1))
.IsNothing()) {
return;
}
}
}
cache->reset(generation);
#endif
env->supported_hash_algorithms.clear();
env->hash_cache_generation = generation;
}
EVP_MD* GetCachedMDByID(Environment* env, size_t id) {
CHECK_LT(id, env->evp_md_cache.size());
EVP_MD* result = env->evp_md_cache[id].get();
CHECK_NOT_NULL(result);
return result;
bool SynchronizeHashCache(Environment* env,
Local<Object> algorithm_cache = Local<Object>()) {
const uint64_t generation = ncrypto::getFipsStateGeneration();
if (env->hash_cache_generation == generation) return false;
ResetHashCache(env, generation, algorithm_cache);
return true;
}
#if NCRYPTO_USE_OPENSSL3_PROVIDER
const EVP_MD* GetCachedMDByID(Environment* env,
int32_t id,
Local<Object> algorithm_cache = Local<Object>()) {
if (SynchronizeHashCache(env, algorithm_cache) ||
env->provider_digest_cache == nullptr) {
return nullptr;
}
return env->provider_digest_cache->lookup(id, env->hash_cache_generation)
.digest;
}
struct MaybeCachedMD {
EVP_MD* explicit_md = nullptr;
const EVP_MD* implicit_md = nullptr;
const EVP_MD* cached_md = nullptr;
ncrypto::Digest digest;
int32_t cache_id = -1;
};
MaybeCachedMD FetchAndMaybeCacheMD(Environment* env, const char* search_name) {
const EVP_MD* implicit_md = ncrypto::getDigestByName(search_name);
if (!implicit_md) return {nullptr, nullptr, -1};
MaybeCachedMD FetchAndMaybeCacheMD(
Environment* env,
const char* search_name,
Local<Object> algorithm_cache = Local<Object>(),
const char* fetch_name = nullptr) {
SynchronizeHashCache(env, algorithm_cache);
if (env->isolate()->HasPendingException()) return {};
ncrypto::DigestCache* cache = env->provider_digest_cache.get();
CHECK_NOT_NULL(cache);
const uint64_t generation = env->hash_cache_generation;
const EVP_MD* legacy = nullptr;
const char* real_name = EVP_MD_get0_name(implicit_md);
if (!real_name) return {nullptr, implicit_md, -1};
auto it = env->alias_to_md_id_map.find(real_name);
if (it != env->alias_to_md_id_map.end()) {
size_t id = it->second;
return {GetCachedMDByID(env, id), implicit_md, static_cast<int32_t>(id)};
if (auto cached = cache->lookup(search_name, generation);
cached.digest != nullptr) {
return {cached.digest, cached.digest, cached.id};
}
// EVP_*_fetch() does not support alias names, so we need to pass it the
// real/original algorithm name.
// We use EVP_*_fetch() as a filter here because it will only return an
// instance if the algorithm is supported by the public OpenSSL APIs (some
// algorithms are used internally by OpenSSL and are also passed to this
// callback).
EVP_MD* explicit_md = EVP_MD_fetch(nullptr, real_name, nullptr);
if (!explicit_md) return {nullptr, implicit_md, -1};
// Cache the EVP_MD* fetched.
env->evp_md_cache.emplace_back(explicit_md);
size_t id = env->evp_md_cache.size() - 1;
// Add all the aliases to the map to speed up next lookup.
std::vector<std::string> aliases;
EVP_MD_names_do_all(explicit_md, PushAliases, &aliases);
for (const auto& alias : aliases) {
env->alias_to_md_id_map.emplace(alias, id);
if (fetch_name == nullptr) {
legacy = ncrypto::getDigestByName(search_name);
if (legacy != nullptr) {
if (legacy == EVP_md_null()) return {};
fetch_name = EVP_MD_get0_name(legacy);
if (fetch_name == nullptr) return {nullptr, legacy, -1};
} else {
fetch_name = search_name;
}
}
env->alias_to_md_id_map.emplace(search_name, id);
return {explicit_md, implicit_md, static_cast<int32_t>(id)};
const ncrypto::Digest digest = ncrypto::Digest::Fetch(fetch_name);
if (!digest) {
return legacy == nullptr ? MaybeCachedMD{}
: MaybeCachedMD{nullptr, legacy, -1};
}
if (generation == ncrypto::getFipsStateGeneration()) {
auto cached = cache->insert(search_name, digest.get(), generation);
if (cached.digest != nullptr) {
return {cached.digest, cached.digest, cached.id};
}
}
return {nullptr, digest, -1};
}
void SaveSupportedHashAlgorithmsAndCacheMD(const EVP_MD* md,
@@ -140,12 +181,57 @@ void SaveSupportedHashAlgorithmsAndCacheMD(const EVP_MD* md,
void* arg) {
if (!from) return;
Environment* env = static_cast<Environment*>(arg);
auto result = FetchAndMaybeCacheMD(env, from);
if (result.explicit_md) {
const ncrypto::Digest legacy = ncrypto::Digest::FromName(from);
const char* canonical_name = legacy ? EVP_MD_get0_name(legacy) : nullptr;
if (canonical_name == nullptr) return;
auto result = FetchAndMaybeCacheMD(env, from, {}, canonical_name);
if (result.cached_md || result.digest) {
env->supported_hash_algorithms.push_back(from);
}
}
struct ProviderHashNameContext {
Environment* env;
};
void SaveSupportedProviderHashName(const char* name, void* arg) {
if (name == nullptr) return;
const std::string_view name_view(name);
const bool is_dotted_decimal =
name_view.find('.') != std::string_view::npos &&
std::all_of(name_view.begin(), name_view.end(), [](unsigned char c) {
return (c >= '0' && c <= '9') || c == '.';
});
if (is_dotted_decimal) return;
std::string normalized_name(name_view);
std::transform(normalized_name.begin(),
normalized_name.end(),
normalized_name.begin(),
[](unsigned char c) {
if (c >= 'A' && c <= 'Z') {
return static_cast<char>(c + ('a' - 'A'));
}
return static_cast<char>(c);
});
auto* context = static_cast<ProviderHashNameContext*>(arg);
auto result = FetchAndMaybeCacheMD(
context->env, normalized_name.c_str(), {}, normalized_name.c_str());
if (result.cached_md || result.digest) {
context->env->supported_hash_algorithms.push_back(normalized_name);
}
}
void SaveSupportedProviderHashAlgorithms(EVP_MD* md, void* arg) {
ProviderHashNameContext context = {
.env = static_cast<Environment*>(arg),
};
EVP_MD_names_do_all(md, SaveSupportedProviderHashName, &context);
}
#else
void SaveSupportedHashAlgorithms(const EVP_MD* md,
const char* from,
@@ -155,25 +241,34 @@ void SaveSupportedHashAlgorithms(const EVP_MD* md,
Environment* env = static_cast<Environment*>(arg);
env->supported_hash_algorithms.push_back(from);
}
#endif // OPENSSL_VERSION_MAJOR >= 3
#endif // NCRYPTO_USE_OPENSSL3_PROVIDER
const std::vector<std::string>& GetSupportedHashAlgorithms(Environment* env) {
if (env->supported_hash_algorithms.empty()) {
MarkPopErrorOnReturn mark_pop_error_on_return;
while (true) {
SynchronizeHashCache(env);
const uint64_t generation = env->hash_cache_generation;
if (env->supported_hash_algorithms.empty()) {
MarkPopErrorOnReturn mark_pop_error_on_return;
#if NCRYPTO_USE_BORINGSSL_EVP_DO_ALL_FALLBACK
for (const auto& digest : kBoringSSLDigests) {
static_cast<void>(digest.get);
env->supported_hash_algorithms.emplace_back(digest.name);
}
#elif OPENSSL_VERSION_MAJOR >= 3
// Since we'll fetch the EVP_MD*, cache them along the way to speed up
// later lookups instead of throwing them away immediately.
EVP_MD_do_all_sorted(SaveSupportedHashAlgorithmsAndCacheMD, env);
for (const auto& digest : kBoringSSLDigests) {
static_cast<void>(digest.get);
env->supported_hash_algorithms.emplace_back(digest.name);
}
#elif NCRYPTO_USE_OPENSSL3_PROVIDER
// Since we'll fetch the EVP_MD*, cache them along the way to speed up
// later lookups instead of throwing them away immediately.
EVP_MD_do_all_sorted(SaveSupportedHashAlgorithmsAndCacheMD, env);
EVP_MD_do_all_provided(nullptr, SaveSupportedProviderHashAlgorithms, env);
#else
EVP_MD_do_all_sorted(SaveSupportedHashAlgorithms, env);
EVP_MD_do_all_sorted(SaveSupportedHashAlgorithms, env);
#endif
}
const uint64_t current_generation = ncrypto::getFipsStateGeneration();
if (generation == current_generation) {
return env->supported_hash_algorithms;
}
ResetHashCache(env, current_generation);
}
return env->supported_hash_algorithms;
}
void Hash::GetHashes(const FunctionCallbackInfo<Value>& args) {
@@ -191,18 +286,19 @@ void Hash::GetCachedAliases(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
Local<Context> context = args.GetIsolate()->GetCurrentContext();
Environment* env = Environment::GetCurrent(context);
size_t size = env->alias_to_md_id_map.size();
SynchronizeHashCache(env);
size_t size = 0;
LocalVector<Name> names(isolate);
LocalVector<Value> values(isolate);
#if OPENSSL_VERSION_MAJOR >= 3
#if NCRYPTO_USE_OPENSSL3_PROVIDER
const auto& aliases = env->provider_digest_cache->aliases();
size = aliases.size();
names.reserve(size);
values.reserve(size);
for (auto& [alias, id] : env->alias_to_md_id_map) {
for (const auto& [alias, id] : aliases) {
names.push_back(OneByteString(isolate, alias));
values.push_back(Uint32::New(isolate, id));
values.push_back(Int32::New(isolate, id));
}
#else
CHECK(env->alias_to_md_id_map.empty());
#endif
Local<Value> prototype = Null(isolate);
Local<Object> result =
@@ -210,18 +306,24 @@ void Hash::GetCachedAliases(const FunctionCallbackInfo<Value>& args) {
args.GetReturnValue().Set(result);
}
const EVP_MD* GetDigestImplementation(Environment* env,
Local<Value> algorithm,
Local<Value> cache_id_val,
Local<Value> algorithm_cache) {
const EVP_MD* GetDigestImplementation(
Environment* env,
Local<Value> algorithm,
Local<Value> cache_id_val,
Local<Value> algorithm_cache,
std::optional<ncrypto::Digest>& digest_owner) {
CHECK(algorithm->IsString());
CHECK(cache_id_val->IsInt32());
CHECK(algorithm_cache->IsObject());
DCHECK(!digest_owner.has_value());
#if OPENSSL_VERSION_MAJOR >= 3
#if NCRYPTO_USE_OPENSSL3_PROVIDER
Local<Object> cache = algorithm_cache.As<Object>();
int32_t cache_id = cache_id_val.As<Int32>()->Value();
if (cache_id != -1) { // Alias already cached, return the cached EVP_MD*.
return GetCachedMDByID(env, cache_id);
if (cache_id != -1) {
// Alias already cached, return the cached EVP_MD*.
if (const EVP_MD* md = GetCachedMDByID(env, cache_id, cache)) return md;
if (env->isolate()->HasPendingException()) return nullptr;
}
// Only decode the algorithm when we don't have it cached to avoid
@@ -229,11 +331,11 @@ const EVP_MD* GetDigestImplementation(Environment* env,
Isolate* isolate = env->isolate();
Utf8Value utf8(isolate, algorithm);
auto result = FetchAndMaybeCacheMD(env, *utf8);
auto result = FetchAndMaybeCacheMD(env, *utf8, cache);
if (env->isolate()->HasPendingException()) return nullptr;
if (result.cache_id != -1) {
// Add the alias to both C++ side and JS side to speedup the lookup
// next time.
env->alias_to_md_id_map.emplace(*utf8, result.cache_id);
// Add the alias to the JavaScript side to speed up the next lookup. The
// native cache added it while inserting the implementation.
if (algorithm_cache.As<Object>()
->Set(isolate->GetCurrentContext(),
algorithm,
@@ -243,7 +345,12 @@ const EVP_MD* GetDigestImplementation(Environment* env,
}
}
return result.explicit_md ? result.explicit_md : result.implicit_md;
if (result.cached_md != nullptr) return result.cached_md;
if (result.digest) {
digest_owner.emplace(result.digest);
return digest_owner->get();
}
return nullptr;
#else
Utf8Value utf8(env->isolate(), algorithm);
return ncrypto::getDigestByName(*utf8);
@@ -257,21 +364,12 @@ void MarkInvalidXofLength() {
EVPerr(EVP_F_EVP_DIGESTFINALXOF, EVP_R_NOT_XOF_OR_INVALID_LENGTH);
#endif
}
// crypto.digest(algorithm, algorithmId, algorithmCache,
// input, outputEncoding, outputEncodingId, outputLength)
void Hash::OneShotDigest(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
Isolate* isolate = env->isolate();
CHECK_EQ(args.Length(), 7);
CHECK(args[0]->IsString()); // algorithm
CHECK(args[1]->IsInt32()); // algorithmId
CHECK(args[2]->IsObject()); // algorithmCache
CHECK(args[3]->IsString() || args[3]->IsArrayBufferView()); // input
CHECK(args[4]->IsString()); // outputEncoding
CHECK(args[5]->IsUint32() || args[5]->IsUndefined()); // outputEncodingId
CHECK(args[6]->IsUint32() || args[6]->IsUndefined()); // outputLength
const EVP_MD* md = GetDigestImplementation(env, args[0], args[1], args[2]);
void OneShotDigestWithMD(Environment* env,
const FunctionCallbackInfo<Value>& args,
const EVP_MD* md,
const CShakeOptions* options) {
Isolate* isolate = env->isolate();
if (md == nullptr) [[unlikely]] {
Utf8Value method(isolate, args[0]);
std::string message =
@@ -313,7 +411,7 @@ void Hash::OneShotDigest(const FunctionCallbackInfo<Value>& args) {
}
}
if (output_length == 0) {
auto return_empty_output = [&]() {
if (output_enc == BUFFER) {
Local<Uint8Array> u8;
if (Buffer::New(isolate, ArrayBuffer::New(isolate, 0), 0, 0)
@@ -323,28 +421,72 @@ void Hash::OneShotDigest(const FunctionCallbackInfo<Value>& args) {
} else {
args.GetReturnValue().Set(String::Empty(isolate));
}
};
const bool has_digest_options = options != nullptr && !options->empty();
if (output_length == 0 && !has_digest_options) {
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);
}
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;
}
DataPointer output = ([&]() -> DataPointer {
EVPMDCtxPointer ctx = EVPMDCtxPointer::New();
if (!options->Initialize(&ctx, md)) {
return ThrowCryptoError(
env, ERR_get_error(), "Digest options are not supported");
}
const bool updated = [&]() {
if (args[3]->IsString()) {
Utf8Value utf8(isolate, args[3]);
ncrypto::Buffer<const unsigned char> buf = {
.data = reinterpret_cast<const unsigned char*>(utf8.out()),
.len = utf8.length(),
};
return is_xof ? ncrypto::xofHashDigest(buf, md, output_length)
: ncrypto::hashDigest(buf, md);
Utf8Value input(isolate, args[3]);
return ctx.digestUpdate(ncrypto::Buffer<const void>{
.data = input.out(),
.len = static_cast<size_t>(input.length()),
});
}
ArrayBufferViewContents<unsigned char> input(args[3]);
ncrypto::Buffer<const unsigned char> buf = {
.data = reinterpret_cast<const unsigned char*>(input.data()),
return ctx.digestUpdate(ncrypto::Buffer<const void>{
.data = input.data(),
.len = input.length(),
};
return is_xof ? ncrypto::xofHashDigest(buf, md, output_length)
: ncrypto::hashDigest(buf, md);
})();
});
}();
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]] {
return ThrowCryptoError(env, ERR_get_error());
@@ -360,6 +502,54 @@ void Hash::OneShotDigest(const FunctionCallbackInfo<Value>& args) {
}
}
// crypto.digest(algorithm, algorithmId, algorithmCache, input, outputEncoding,
// outputEncodingId, outputLength[, functionName, customization])
void Hash::OneShotDigest(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
CHECK(args.Length() == 7 || args.Length() == 9);
CHECK(args[0]->IsString()); // algorithm
CHECK(args[1]->IsInt32()); // algorithmId
CHECK(args[2]->IsObject()); // algorithmCache
CHECK(args[3]->IsString() || args[3]->IsArrayBufferView()); // input
CHECK(args[4]->IsString()); // outputEncoding
CHECK(args[5]->IsUint32() || args[5]->IsUndefined()); // outputEncodingId
CHECK(args[6]->IsUint32() || args[6]->IsUndefined()); // outputLength
if (args.Length() == 7) {
#if NCRYPTO_USE_OPENSSL3_PROVIDER
const int32_t cache_id = args[1].As<Int32>()->Value();
if (cache_id != -1) {
if (const EVP_MD* md =
GetCachedMDByID(env, cache_id, args[2].As<Object>())) {
return OneShotDigestWithMD(env, args, md, nullptr);
}
if (env->isolate()->HasPendingException()) return;
}
#else
Utf8Value utf8(env->isolate(), args[0]);
return OneShotDigestWithMD(
env, args, ncrypto::getDigestByName(*utf8), nullptr);
#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);
}
void Hash::Initialize(Environment* env, Local<Object> target) {
Isolate* isolate = env->isolate();
Local<Context> context = env->context();
@@ -396,19 +586,11 @@ void Hash::RegisterExternalReferences(ExternalReferenceRegistry* registry) {
#endif
}
// new Hash(algorithm, algorithmId, xofLen, algorithmCache)
// new Hash(algorithm, xofLen, algorithmId, algorithmCache[, functionName,
// customization])
void Hash::New(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
const Hash* orig = nullptr;
const EVP_MD* md = nullptr;
if (args[0]->IsObject()) {
ASSIGN_OR_RETURN_UNWRAP(&orig, args[0].As<Object>());
CHECK_NOT_NULL(orig);
md = orig->mdctx_.getDigest();
} else {
md = GetDigestImplementation(env, args[0], args[2], args[3]);
}
CHECK(args.Length() == 4 || args.Length() == 6);
Maybe<unsigned int> xof_md_len = Nothing<unsigned int>();
if (!args[1]->IsUndefined()) {
@@ -416,10 +598,52 @@ void Hash::New(const FunctionCallbackInfo<Value>& args) {
xof_md_len = Just<unsigned int>(args[1].As<Uint32>()->Value());
}
#if NCRYPTO_USE_OPENSSL3_PROVIDER
// This is the common path after the first lookup. Avoid constructing a
// digest owner when the Environment already owns the cached implementation.
if (args.Length() == 4 && args[0]->IsString()) {
CHECK(args[2]->IsInt32());
const int32_t cache_id = args[2].As<Int32>()->Value();
if (cache_id != -1) {
if (const EVP_MD* md =
GetCachedMDByID(env, cache_id, args[3].As<Object>())) {
Hash* hash = new Hash(env, args.This());
if (!hash->HashInit(md, xof_md_len)) {
return ThrowCryptoError(
env, ERR_get_error(), "Digest method not supported");
}
return;
}
if (env->isolate()->HasPendingException()) return;
}
}
#endif
const Hash* orig = nullptr;
std::optional<ncrypto::Digest> digest_owner;
const EVP_MD* md = nullptr;
if (args[0]->IsObject()) {
ASSIGN_OR_RETURN_UNWRAP(&orig, args[0].As<Object>());
CHECK_NOT_NULL(orig);
md = orig->mdctx_.getDigest();
} else {
md = GetDigestImplementation(env, args[0], args[2], args[3], digest_owner);
if (env->isolate()->HasPendingException()) return;
}
Hash* hash = new Hash(env, args.This());
if (md == nullptr || !hash->HashInit(md, xof_md_len)) {
return ThrowCryptoError(env, ERR_get_error(),
"Digest method not supported");
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");
}
}
if (orig != nullptr && !orig->mdctx_.copyTo(hash->mdctx_)) {
@@ -427,9 +651,9 @@ void Hash::New(const FunctionCallbackInfo<Value>& args) {
}
}
bool Hash::HashInit(const EVP_MD* md, Maybe<unsigned int> xof_md_len) {
bool Hash::HashInit(const EVP_MD* digest, Maybe<unsigned int> xof_md_len) {
mdctx_ = EVPMDCtxPointer::New();
if (!mdctx_.digestInit(md)) [[unlikely]] {
if (!mdctx_.digestInit(digest)) [[unlikely]] {
mdctx_.reset();
return false;
}
@@ -440,7 +664,7 @@ bool Hash::HashInit(const EVP_MD* md, Maybe<unsigned int> xof_md_len) {
// default lengths
// TODO(@panva): remove this behaviour when DEP0198 is End-Of-Life
if (mdctx_.hasXofFlag() && !xof_md_len.IsJust() && md_len_ == 0) {
const char* name = OBJ_nid2sn(EVP_MD_type(md));
const char* name = OBJ_nid2sn(EVP_MD_type(digest));
if (name != nullptr) {
if (strcmp(name, "SHAKE128") == 0) {
md_len_ = 16;
@@ -464,6 +688,30 @@ bool Hash::HashInit(const EVP_MD* md, Maybe<unsigned int> xof_md_len) {
return true;
}
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;
}
md_len_ = mdctx_.getDigestSize();
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;
}
bool Hash::HashUpdate(const char* data, size_t len) {
if (!mdctx_) return false;
return mdctx_.digestUpdate(ncrypto::Buffer<const void>{
@@ -528,7 +776,10 @@ void Hash::HashDigest(const FunctionCallbackInfo<Value>& args) {
}
HashConfig::HashConfig(HashConfig&& other) noexcept
: in(std::move(other.in)), digest(other.digest), length(other.length) {}
: in(std::move(other.in)),
digest(other.digest),
options(std::move(other.options)),
length(other.length) {}
HashConfig& HashConfig::operator=(HashConfig&& other) noexcept {
if (&other == this) return *this;
@@ -538,6 +789,9 @@ HashConfig& HashConfig::operator=(HashConfig&& other) noexcept {
void HashConfig::MemoryInfo(MemoryTracker* tracker) const {
tracker->TraitTrackInline(in, "in");
if (options.has_value()) {
tracker->TrackField("options", *options);
}
}
MaybeLocal<Value> HashTraits::EncodeOutput(Environment* env,
@@ -555,8 +809,8 @@ Maybe<void> HashTraits::AdditionalConfig(
CHECK(args[offset]->IsString()); // Hash algorithm
Utf8Value digest(env->isolate(), args[offset]);
params->digest = ncrypto::getDigestByName(*digest);
if (params->digest == nullptr) [[unlikely]] {
params->digest = ncrypto::Digest::FromName(*digest);
if (!params->digest) [[unlikely]] {
THROW_ERR_CRYPTO_INVALID_DIGEST(env, "Invalid digest: %s", digest);
return Nothing<void>();
}
@@ -568,7 +822,14 @@ Maybe<void> HashTraits::AdditionalConfig(
}
params->in = IsCryptoJobAsync(mode) ? data.ToCopy() : data.ToByteSource();
unsigned int expected = EVP_MD_size(params->digest);
if (static_cast<unsigned int>(args.Length()) > offset + 3) {
params->options.emplace();
if (GetCShakeOptions(args, offset + 3, &*params->options).IsNothing()) {
return Nothing<void>();
}
}
unsigned int expected = EVP_MD_size(params->digest.get());
params->length = expected;
if (args[offset + 2]->IsUint32()) [[unlikely]] {
// length is expressed in terms of bits
@@ -576,7 +837,8 @@ Maybe<void> HashTraits::AdditionalConfig(
static_cast<uint32_t>(args[offset + 2].As<Uint32>()->Value()) /
CHAR_BIT;
if (params->length != expected) {
if ((EVP_MD_flags(params->digest) & EVP_MD_FLAG_XOF) == 0) [[unlikely]] {
if ((EVP_MD_flags(params->digest.get()) & EVP_MD_FLAG_XOF) == 0)
[[unlikely]] {
THROW_ERR_CRYPTO_INVALID_DIGEST(env, "Digest method not supported");
return Nothing<void>();
}
@@ -593,8 +855,11 @@ bool HashTraits::DeriveBits(Environment* env,
CryptoErrorStore* errors) {
auto ctx = EVPMDCtxPointer::New();
if (!ctx.digestInit(params.digest) || !ctx.digestUpdate(params.in))
[[unlikely]] {
const bool initialized =
params.options.has_value()
? params.options->Initialize(&ctx, params.digest.get())
: ctx.digestInit(params.digest.get());
if (!initialized || !ctx.digestUpdate(params.in)) [[unlikely]] {
return false;
}
+6 -2
View File
@@ -21,7 +21,10 @@ class Hash final : public BaseObject {
SET_MEMORY_INFO_NAME(Hash)
SET_SELF_SIZE(Hash)
bool HashInit(const EVP_MD* md, v8::Maybe<unsigned int> xof_md_len);
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);
bool HashUpdate(const char* data, size_t len);
static void GetHashes(const v8::FunctionCallbackInfo<v8::Value>& args);
@@ -43,7 +46,8 @@ class Hash final : public BaseObject {
struct HashConfig final : public MemoryRetainer {
ByteSource in;
const EVP_MD* digest;
ncrypto::Digest digest;
std::optional<CShakeOptions> options;
unsigned int length;
HashConfig() = default;
+19 -2
View File
@@ -38,6 +38,21 @@ using v8::Uint32;
using v8::Value;
namespace crypto {
namespace {
bool IsRsaPssDigestEncodable(const Digest& digest) {
#if NCRYPTO_USE_OPENSSL3_PROVIDER
const int nid = EVP_MD_type(digest.get());
if (nid == NID_undef) return false;
const ASN1_OBJECT* object = OBJ_nid2obj(nid);
return object != nullptr && OBJ_length(object) > 0;
#else
static_cast<void>(digest);
return true;
#endif
}
} // namespace
EVPKeyCtxPointer RsaKeyGenTraits::Setup(RsaKeyPairGenConfig* params) {
auto ctx = EVPKeyCtxPointer::NewFromID(
params->params.variant == kKeyVariantRSA_PSS ? EVP_PKEY_RSA_PSS
@@ -58,7 +73,8 @@ EVPKeyCtxPointer RsaKeyGenTraits::Setup(RsaKeyPairGenConfig* params) {
}
if (params->params.variant == kKeyVariantRSA_PSS) {
if (params->params.md && !ctx.setRsaPssKeygenMd(params->params.md)) {
if (params->params.md && (!IsRsaPssDigestEncodable(params->params.md) ||
!ctx.setRsaPssKeygenMd(params->params.md))) {
return {};
}
@@ -71,7 +87,8 @@ EVPKeyCtxPointer RsaKeyGenTraits::Setup(RsaKeyPairGenConfig* params) {
mgf1_md = params->params.md;
}
if (mgf1_md && !ctx.setRsaPssKeygenMgf1Md(mgf1_md)) {
if (mgf1_md && (!IsRsaPssDigestEncodable(mgf1_md) ||
!ctx.setRsaPssKeygenMgf1Md(mgf1_md))) {
return {};
}
+115
View File
@@ -18,6 +18,11 @@
#include "openssl/provider.h"
#endif
#if !defined(OPENSSL_IS_BORINGSSL) && OPENSSL_VERSION_PREREQ(4, 0)
#include <openssl/core_names.h>
#include <openssl/params.h>
#endif
namespace node {
using ncrypto::BignumPointer;
@@ -76,6 +81,108 @@ 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());
}
bool CShakeOptions::Initialize(ncrypto::EVPMDCtxPointer* ctx,
const EVP_MD* digest) const {
if (!ctx || !*ctx || digest == nullptr) return false;
if (empty()) return ctx->digestInit(digest);
#if !defined(OPENSSL_IS_BORINGSSL) && OPENSSL_VERSION_PREREQ(4, 0)
const bool is_cshake =
EVP_MD_is_a(digest, "CSHAKE-128") || EVP_MD_is_a(digest, "CSHAKE-256");
if (!is_cshake) return false;
OSSL_PARAM params[3];
size_t count = 0;
if (has(kFunctionName)) {
params[count++] = OSSL_PARAM_construct_utf8_string(
OSSL_DIGEST_PARAM_FUNCTION_NAME,
const_cast<char*>(function_name.c_str()),
function_name.size());
}
if (has(kCustomization)) {
params[count++] = OSSL_PARAM_construct_utf8_string(
OSSL_DIGEST_PARAM_CUSTOMIZATION,
const_cast<char*>(customization.c_str()),
customization.size());
}
params[count] = OSSL_PARAM_construct_end();
return ctx->digestInit(digest, params);
#else
return false;
#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();
}
} // namespace
v8::Maybe<void> GetCShakeOptions(
const v8::FunctionCallbackInfo<v8::Value>& args,
unsigned int offset,
CShakeOptions* 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>();
}
return v8::JustVoid();
}
int PasswordCallback(char* buf, int size, int rwflag, void* u) {
const ByteSource* passphrase = *static_cast<const ByteSource**>(u);
if (passphrase != nullptr) {
@@ -231,6 +338,11 @@ void GetFipsCrypto(const FunctionCallbackInfo<Value>& args) {
args.GetReturnValue().Set(IsFipsEnabled() ? 1 : 0);
}
void GetFipsCryptoGeneration(const FunctionCallbackInfo<Value>& args) {
args.GetReturnValue().Set(BigInt::NewFromUnsigned(
args.GetIsolate(), ncrypto::getFipsStateGeneration()));
}
void SetFipsCrypto(const FunctionCallbackInfo<Value>& args) {
Mutex::ScopedLock lock(per_process::cli_options_mutex);
Mutex::ScopedLock fips_lock(fips_mutex);
@@ -891,6 +1003,8 @@ void Initialize(Environment* env, Local<Object> target) {
#endif // !OPENSSL_NO_ENGINE
SetMethodNoSideEffect(context, target, "getFipsCrypto", GetFipsCrypto);
SetMethodNoSideEffect(
context, target, "getFipsCryptoGeneration", GetFipsCryptoGeneration);
SetMethod(context, target, "setFipsCrypto", SetFipsCrypto);
SetMethodNoSideEffect(context, target, "testFipsCrypto", TestFipsCrypto);
@@ -910,6 +1024,7 @@ void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
#endif // !OPENSSL_NO_ENGINE
registry->Register(GetFipsCrypto);
registry->Register(GetFipsCryptoGeneration);
registry->Register(SetFipsCrypto);
registry->Register(TestFipsCrypto);
registry->Register(SecureBuffer);
+29
View File
@@ -286,6 +286,35 @@ 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,
};
std::string function_name;
std::string customization;
uint8_t flags = 0;
CShakeOptions() = default;
CShakeOptions(CShakeOptions&& other) noexcept;
CShakeOptions& operator=(CShakeOptions&& other) noexcept;
bool empty() const { return flags == 0; }
bool has(Flag flag) const { return (flags & flag) != 0; }
bool Initialize(ncrypto::EVPMDCtxPointer* ctx, const EVP_MD* digest) const;
void MemoryInfo(MemoryTracker* tracker) const override;
SET_MEMORY_INFO_NAME(CShakeOptions)
SET_SELF_SIZE(CShakeOptions)
};
v8::Maybe<void> GetCShakeOptions(
const v8::FunctionCallbackInfo<v8::Value>& args,
unsigned int offset,
CShakeOptions* options);
v8::MaybeLocal<v8::Value> CreateWebCryptoJobError(Environment* env,
v8::Local<v8::Value> cause);
+12
View File
@@ -16,6 +16,9 @@
#include "node_snapshotable.h"
#include "node_v8_platform-inl.h"
#include "node_worker.h"
#if HAVE_OPENSSL
#include "ncrypto.h"
#endif
#include "req_wrap-inl.h"
#include "stream_base.h"
#include "tracing/agent.h"
@@ -878,6 +881,10 @@ Environment::Environment(IsolateData* isolate_data,
? AllocateEnvironmentThreadId().id
: thread_id.id),
thread_name_(thread_name) {
#if HAVE_OPENSSL && NCRYPTO_USE_OPENSSL3_PROVIDER
provider_digest_cache = std::make_unique<ncrypto::DigestCache>();
#endif
if (!is_main_thread()) {
// If this is a Worker thread, we can always safely use the parent's
// Isolate's code cache because of the shared read-only heap.
@@ -1129,6 +1136,11 @@ Environment::~Environment() {
// Also, since the main thread usually stops just before the process exits,
// this is far less relevant here.
if (!is_main_thread()) {
#if HAVE_OPENSSL
// Provider methods can contain callbacks into native addons. Release the
// environment-owned methods before unloading any addon DSOs.
provider_digest_cache.reset();
#endif
// Dereference all addons that were loaded into this environment.
for (binding::DLib& addon : loaded_addons_) {
addon.Close();
+6 -10
View File
@@ -53,10 +53,6 @@
#include "v8-profiler.h"
#include "v8.h"
#if HAVE_OPENSSL
#include <openssl/evp.h>
#endif
#include <array>
#include <atomic>
#include <cstdint>
@@ -72,6 +68,10 @@
#include <variant>
#include <vector>
namespace ncrypto {
class DigestCache;
} // namespace ncrypto
namespace node {
namespace shadow_realm {
@@ -1093,12 +1093,8 @@ class Environment final : public MemoryRetainer {
};
#if HAVE_OPENSSL
#if OPENSSL_VERSION_MAJOR >= 3
// We declare another alias here to avoid having to include crypto_util.h
using EVPMDPointer = DeleteFnPtr<EVP_MD, EVP_MD_free>;
std::vector<EVPMDPointer> evp_md_cache;
#endif // OPENSSL_VERSION_MAJOR >= 3
std::unordered_map<std::string, size_t> alias_to_md_id_map;
uint64_t hash_cache_generation = 0;
std::unique_ptr<ncrypto::DigestCache> provider_digest_cache;
std::vector<std::string> supported_hash_algorithms;
#endif // HAVE_OPENSSL
+1
View File
@@ -14,6 +14,7 @@ openssl-binding/test: PASS,FLAKY
openssl-binding/test: SKIP
openssl-get-ssl-ctx/test: SKIP
openssl-providers/test-default-only-config: SKIP
openssl-providers/test-default-properties-config: SKIP
openssl-providers/test-legacy-provider-config: SKIP
openssl-providers/test-legacy-provider-inactive-config: SKIP
openssl-providers/test-legacy-provider-option: SKIP
+15 -2
View File
@@ -21,7 +21,11 @@ const { getProviders } = require(`./build/${common.buildType}/binding`);
const providers = {
'default': {
ciphers: ['des3-wrap'],
hashes: ['sha512-256'],
hashes: [
'sha512-256',
...['keccak-kmac-128', 'keccak-kmac128']
.filter((name) => getHashes().includes(name)),
],
},
'legacy': {
ciphers: ['blowfish', 'idea'],
@@ -47,6 +51,15 @@ function assertArrayIncludes(array, item, desc) {
`${desc} [${array}] does not include "${item}"`);
}
function createSupportedHash(hash) {
try {
return createHash(hash);
} catch (err) {
if (err?.code !== 'ERR_OSSL_EVP_NOT_XOF_OR_INVALID_LENGTH') throw err;
return createHash(hash, { outputLength: 32 });
}
}
function testProviderPresent(provider) {
debug(`Checking '${provider}' is present`);
assertArrayIncludes(getProviders(), provider, 'Loaded providers');
@@ -57,7 +70,7 @@ function testProviderPresent(provider) {
for (const hash of providers[provider].hashes || []) {
debug(`Checking '${hash}' hash is available`);
assertArrayIncludes(getHashes(), hash, 'Available hashes');
createHash(hash);
createSupportedHash(hash);
}
}
@@ -0,0 +1,158 @@
// Flags: --expose-internals
'use strict';
const common = require('../../common');
const fixtures = require('../../common/fixtures');
const providers = require('./providers.cjs');
const assert = require('node:assert');
const { fork } = require('node:child_process');
const {
createHash,
getHashes,
hash: oneShotHash,
setFips,
} = require('node:crypto');
const { Worker } = require('node:worker_threads');
const { getHashCache } = require('internal/crypto/util');
const option = `--openssl-config=${fixtures.path(
'openssl3-conf',
'default_properties.cnf',
)}`;
if (!process.execArgv.includes(option)) {
const cp = fork(__filename, { execArgv: [...process.execArgv, option] });
cp.on('exit', common.mustCall((code, signal) => {
assert.strictEqual(code, 0);
assert.strictEqual(signal, null);
}));
return;
}
assert(providers.getCurrentProviders().includes('default'));
assert(providers.getCurrentProviders().includes('legacy'));
providers.testProviderPresent('default');
const hashes = getHashes();
const input = Buffer.alloc(0);
const md5 = 'd41d8cd98f00b204e9800998ecf8427e';
assert.strictEqual(createHash('md5').update(input).digest('hex'), md5);
assert.strictEqual(oneShotHash('md5', input), md5);
const hashName = 'SHA256';
const hashCache = getHashCache();
const descriptor = Object.getOwnPropertyDescriptor(hashCache, hashName);
assert(descriptor);
const cacheId = descriptor.value;
const sentinel = new Error('hash cache setter');
const throwsSentinel = (err) => err === sentinel;
function installThrowingHashCacheEntry(id) {
Object.defineProperty(hashCache, hashName, {
__proto__: null,
configurable: true,
enumerable: descriptor.enumerable,
get() { return id; },
set() { throw sentinel; },
});
}
installThrowingHashCacheEntry(-1);
assert.throws(() => createHash(hashName), throwsSentinel);
assert.throws(() => oneShotHash(hashName, input), throwsSentinel);
Object.defineProperty(hashCache, hashName, descriptor);
installThrowingHashCacheEntry(cacheId);
setFips(true);
assert.throws(() => createHash(hashName), throwsSentinel);
assert.throws(() => oneShotHash(hashName, input), throwsSentinel);
Object.defineProperty(hashCache, hashName, descriptor);
assert.deepStrictEqual(getHashes(), []);
assert.throws(
() => createHash('md5'),
{ code: 'ERR_OSSL_EVP_UNSUPPORTED' },
);
assert.throws(
() => oneShotHash('md5', input),
{ code: 'ERR_OSSL_EVP_UNSUPPORTED' },
);
setFips(false);
assert.deepStrictEqual(getHashes(), hashes);
assert.strictEqual(createHash('md5').update(input).digest('hex'), md5);
assert.strictEqual(oneShotHash('md5', input), md5);
for (const hash of ['md4', 'whirlpool']) {
assert(!hashes.includes(hash));
assert.throws(() => createHash(hash), { code: 'ERR_OSSL_EVP_UNSUPPORTED' });
}
const worker = new Worker(`
'use strict';
const {
createHash,
getHashes,
hash,
} = require('node:crypto');
const { parentPort } = require('node:worker_threads');
const input = Buffer.alloc(0);
const hashes = getHashes();
const liveHash = createHash('md5').update(input);
hash('md5', input);
parentPort.postMessage({ phase: 'warm' });
function getErrorCode(fn) {
try {
fn();
} catch (err) {
return err.code;
}
}
parentPort.on('message', (phase) => {
if (phase === 'fips-on') {
parentPort.postMessage({
phase,
createHashError: getErrorCode(() => createHash('md5')),
oneShotHashError: getErrorCode(() => hash('md5', input)),
hashes: getHashes(),
liveDigest: liveHash.digest('hex'),
});
} else {
parentPort.postMessage({
phase,
createHashDigest: createHash('md5').update(input).digest('hex'),
oneShotHashDigest: hash('md5', input),
hashes: getHashes(),
});
parentPort.close();
}
});
`, { eval: true });
worker.once('message', common.mustCall((message) => {
assert.strictEqual(message.phase, 'warm');
setFips(true);
worker.once('message', common.mustCall((message) => {
assert.strictEqual(message.phase, 'fips-on');
assert.strictEqual(message.createHashError, 'ERR_OSSL_EVP_UNSUPPORTED');
assert.strictEqual(message.oneShotHashError, 'ERR_OSSL_EVP_UNSUPPORTED');
assert.deepStrictEqual(message.hashes, []);
assert.strictEqual(message.liveDigest, md5);
setFips(false);
worker.once('message', common.mustCall((message) => {
assert.strictEqual(message.phase, 'fips-off');
assert.strictEqual(message.createHashDigest, md5);
assert.strictEqual(message.oneShotHashDigest, md5);
assert.deepStrictEqual(message.hashes, hashes);
}));
worker.postMessage('fips-off');
}));
worker.postMessage('fips-on');
}));
worker.on('error', common.mustNotCall());
worker.on('exit', common.mustCall((code) => assert.strictEqual(code, 0)));
+19
View File
@@ -0,0 +1,19 @@
nodejs_conf = nodejs_init
[nodejs_init]
providers = provider_sect
alg_section = algorithm_sect
# Load both providers but select only implementations from the default provider.
[provider_sect]
default = default_sect
legacy = legacy_sect
[default_sect]
activate = 1
[legacy_sect]
activate = 1
[algorithm_sect]
default_properties = provider=default
@@ -0,0 +1,387 @@
// Flags: --expose-internals
'use strict';
const common = require('../common');
if (!common.hasCrypto) {
common.skip('missing crypto');
}
if (Number(process.versions.openssl.split('.')[0]) < 4 ||
process.features.openssl_is_boringssl) {
common.skip('OpenSSL 4 provider support is required');
}
const assert = require('node:assert');
const {
createHash,
getHashes,
hash,
} = require('node:crypto');
const { internalBinding } = require('internal/test/binding');
const {
HashJob,
kCryptoJobSync,
kCryptoJobWebCrypto,
} = internalBinding('crypto');
const hashes = getHashes();
const hashNames = new Map(
hashes.map((name) => [name.toLowerCase(), name]),
);
let exercised = false;
function findHash(...names) {
for (const name of names) {
const result = hashNames.get(name);
if (result !== undefined) return result;
}
return undefined;
}
function testHashJob(args, expected) {
const { 0: err, 1: result } = new HashJob(
kCryptoJobSync,
...args,
).run();
assert.strictEqual(err, undefined);
assert.deepStrictEqual(Buffer.from(result), expected);
(async () => {
const asyncResult = await new HashJob(
kCryptoJobWebCrypto,
...args,
).run();
assert.deepStrictEqual(Buffer.from(asyncResult), expected);
})().then(common.mustCall());
}
const cshakeVectors = [
{
names: ['cshake-128', 'cshake128'],
shakeNames: ['shake128', 'shake-128'],
outputLength: 32,
input: Buffer.from('00010203', 'hex'),
expected: 'c1c36925b6409a04f1b504fcbca9d82b' +
'4017277cb5ed2b2065fc1d3814d5aaf5',
},
{
names: ['cshake-256', 'cshake256'],
shakeNames: ['shake256', 'shake-256'],
outputLength: 64,
input: Buffer.from('00010203', 'hex'),
expected: 'd008828e2b80ac9d2218ffee1d070c48' +
'b8e4c87bff32c9699d5b6896eee0edd1' +
'64020e2be0560858d9c00c037e34a96' +
'937c561a74c412bb4c746469527281c8c',
},
];
for (const vector of cshakeVectors) {
const algorithm = findHash(...vector.names);
if (algorithm === undefined) {
common.printSkipMessage(`${vector.names[0]} is not available`);
continue;
}
exercised = true;
const options = {
outputLength: vector.outputLength,
customization: 'Email Signature',
};
const streaming = createHash(algorithm, options)
.update(vector.input.subarray(0, 2))
.update(vector.input.subarray(2))
.digest('hex');
const partial = createHash(algorithm, options)
.update(vector.input.subarray(0, 2));
const copyOptionReads = [];
const copied = partial.copy({
get outputLength() {
copyOptionReads.push('outputLength');
return vector.outputLength;
},
get functionName() {
copyOptionReads.push('functionName');
return undefined;
},
get customization() {
copyOptionReads.push('customization');
return undefined;
},
})
.update(vector.input.subarray(2))
.digest('hex');
assert.strictEqual(streaming, vector.expected);
assert.strictEqual(copied, vector.expected);
assert.deepStrictEqual(copyOptionReads, ['outputLength']);
assert.strictEqual(hash(algorithm, vector.input, options), vector.expected);
// BufferSource parameters have the same semantics as their string form.
const bufferOptions = {
...options,
customization: Buffer.from(options.customization),
};
assert.strictEqual(
createHash(algorithm, bufferOptions).update(vector.input).digest('hex'),
vector.expected,
);
assert.strictEqual(
hash(algorithm, vector.input, bufferOptions),
vector.expected,
);
// Without function-name and customization parameters, cSHAKE is SHAKE.
const withoutParameters = createHash(algorithm)
.update(vector.input)
.digest('hex');
assert.strictEqual(hash(algorithm, vector.input), withoutParameters);
// Explicit undefined parameters have the same semantics as omitted ones.
const undefinedOptions = {
outputLength: vector.outputLength,
functionName: undefined,
customization: undefined,
};
assert.strictEqual(
createHash(algorithm, undefinedOptions).update(vector.input).digest('hex'),
withoutParameters,
);
assert.strictEqual(
hash(algorithm, vector.input, undefinedOptions),
withoutParameters,
);
// Empty BufferSource parameters are still supplied to OpenSSL, but cSHAKE
// with two empty parameters is equivalent to SHAKE.
const emptyOptions = {
outputLength: vector.outputLength,
functionName: Buffer.alloc(0),
customization: new Uint8Array(0),
};
assert.strictEqual(
createHash(algorithm, emptyOptions).update(vector.input).digest('hex'),
withoutParameters,
);
assert.strictEqual(
hash(algorithm, vector.input, emptyOptions),
withoutParameters,
);
const emptyFunctionNameOptions = {
outputLength: vector.outputLength,
functionName: Buffer.alloc(0),
};
assert.strictEqual(
createHash(algorithm, emptyFunctionNameOptions)
.update(vector.input)
.digest('hex'),
withoutParameters,
);
assert.strictEqual(
hash(algorithm, vector.input, emptyFunctionNameOptions),
withoutParameters,
);
const createHashOptionReads = [];
assert.strictEqual(
createHash(algorithm, {
get outputLength() {
createHashOptionReads.push('outputLength');
return vector.outputLength;
},
get functionName() {
createHashOptionReads.push('functionName');
return undefined;
},
get customization() {
createHashOptionReads.push('customization');
return undefined;
},
}).update(vector.input).digest('hex'),
withoutParameters,
);
assert.deepStrictEqual(
createHashOptionReads,
['outputLength', 'functionName', 'customization'],
);
const hashOptionReads = [];
assert.strictEqual(
hash(algorithm, vector.input, {
get outputLength() {
hashOptionReads.push('outputLength');
return vector.outputLength;
},
get outputEncoding() {
hashOptionReads.push('outputEncoding');
return 'hex';
},
get functionName() {
hashOptionReads.push('functionName');
return undefined;
},
get customization() {
hashOptionReads.push('customization');
return undefined;
},
}),
withoutParameters,
);
assert.deepStrictEqual(
hashOptionReads,
['outputLength', 'outputEncoding', 'functionName', 'customization'],
);
for (const zeroLengthOptions of [
{ outputLength: 0 },
{
outputLength: 0,
functionName: Buffer.alloc(0),
customization: new Uint8Array(0),
},
]) {
assert.deepStrictEqual(
createHash(algorithm, zeroLengthOptions).update(vector.input).digest(),
Buffer.alloc(0),
);
assert.strictEqual(
hash(algorithm, vector.input, zeroLengthOptions),
'',
);
}
const shake = findHash(...vector.shakeNames);
if (shake !== undefined) {
assert.strictEqual(
withoutParameters,
createHash(shake, { outputLength: vector.outputLength })
.update(vector.input)
.digest('hex'),
);
}
const namedOptions = {
outputLength: vector.outputLength,
functionName: 'KMAC',
customization: 'Node.js',
};
let namedResult;
try {
namedResult = createHash(algorithm, namedOptions)
.update(vector.input)
.digest();
} catch {
common.printSkipMessage(
`${algorithm} does not support the KMAC function name`,
);
}
if (namedResult !== undefined) {
assert.deepStrictEqual(
hash(algorithm, vector.input, {
...namedOptions,
outputEncoding: 'buffer',
}),
namedResult,
);
assert.deepStrictEqual(
createHash(algorithm, {
...namedOptions,
functionName: Buffer.from(namedOptions.functionName),
customization: new Uint8Array(Buffer.from(namedOptions.customization)),
}).update(vector.input).digest(),
namedResult,
);
assert.deepStrictEqual(
hash(algorithm, vector.input, {
...namedOptions,
functionName: Buffer.from(namedOptions.functionName),
customization: new Uint8Array(Buffer.from(namedOptions.customization)),
outputEncoding: 'buffer',
}),
namedResult,
);
}
for (const functionName of ['', 'TupleHash', 'ParallelHash', 'KMAC']) {
const functionOptions = {
outputLength: vector.outputLength,
functionName,
};
let functionResult;
try {
functionResult = createHash(algorithm, functionOptions)
.update(vector.input)
.digest();
} catch {
common.printSkipMessage(
`${algorithm} does not support the ${functionName} function name`,
);
continue;
}
assert.deepStrictEqual(
functionResult,
hash(algorithm, vector.input, {
...functionOptions,
outputEncoding: 'buffer',
}),
);
}
testHashJob([
algorithm,
vector.input,
vector.outputLength * 8,
undefined,
Buffer.from(options.customization),
], Buffer.from(vector.expected, 'hex'));
for (const invalidOptions of [
{ functionName: 1 },
{ customization: {} },
]) {
const expected = { code: 'ERR_INVALID_ARG_TYPE' };
assert.throws(() => createHash(algorithm, invalidOptions), expected);
assert.throws(
() => hash(algorithm, vector.input, invalidOptions),
expected,
);
}
for (const invalidOptions of [
{ functionName: 'KMAC\0' },
{ customization: 'Node\0js' },
{ customization: Buffer.from([0x61, 0x00, 0x62]) },
]) {
const expected = { code: 'ERR_INVALID_ARG_VALUE' };
assert.throws(() => createHash(algorithm, invalidOptions), expected);
assert.throws(
() => hash(algorithm, vector.input, invalidOptions),
expected,
);
}
}
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');
}
@@ -0,0 +1,258 @@
// Flags: --expose-internals
'use strict';
const common = require('../common');
if (!common.hasCrypto) {
common.skip('missing crypto');
}
const assert = require('node:assert');
const {
createHash,
createHmac,
createSign,
createVerify,
generateKeyPair,
generateKeyPairSync,
getHashes,
hash,
hkdf,
hkdfSync,
pbkdf2,
pbkdf2Sync,
privateDecrypt,
publicEncrypt,
sign,
verify,
} = require('node:crypto');
const { hasOpenSSL3 } = require('../common/crypto');
if (!hasOpenSSL3 || process.features.openssl_is_boringssl) {
common.skip('OpenSSL 3 provider support is required');
}
const { internalBinding } = require('internal/test/binding');
const {
HashJob,
kCryptoJobSync,
kCryptoJobWebCrypto,
} = internalBinding('crypto');
const hashes = getHashes();
const lowercaseHashes = hashes.map((name) => name.toLowerCase());
const modifiedHashes = getHashes();
modifiedHashes.length = 0;
assert.deepStrictEqual(hashes, [...hashes].sort());
assert.deepStrictEqual(getHashes(), hashes);
assert.strictEqual(new Set(lowercaseHashes).size, hashes.length);
if (lowercaseHashes.includes('sha1')) {
assert(hashes.includes('RSA-SHA1'));
}
assert(!lowercaseHashes.includes('null'));
assert(!lowercaseHashes.includes('ml-dsa-mu'));
assert(!hashes.some((name) => /^\d+(?:\.\d+)+$/.test(name)));
for (const name of hashes) {
try {
createHash(name);
} catch (err) {
assert.strictEqual(err.code, 'ERR_OSSL_EVP_NOT_XOF_OR_INVALID_LENGTH');
createHash(name, { outputLength: 32 });
}
}
const input = Buffer.alloc(0);
assert.throws(
() => createHash('ml-dsa-mu'),
/Digest method not supported/,
);
assert.throws(
() => hash('ml-dsa-mu', input),
{ message: 'Digest method ml-dsa-mu is not supported' },
);
const providerVectors = {
'keccak-kmac-128': {
aliases: ['keccak-kmac-128', 'keccak-kmac128'],
expected: '83aa04c211dc19d16912571ed0a75130' +
'd36aebd58562dd080c1ea84a8c7d73f7',
options: { outputLength: 32 },
},
'keccak-256': {
aliases: ['keccak-256'],
expected: 'c5d2460186f7233c927e7db2dcc703c0' +
'e500b653ca82273b7bfad8045d85a470',
},
'sha256-192': {
aliases: ['sha2-256/192', 'sha-256/192', 'sha256-192'],
expected: 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934c',
},
};
function testHashVector({ aliases, expected, options }) {
for (const alias of aliases) {
if (!hashes.includes(alias)) continue;
assert(!hashes.includes(alias.toUpperCase()));
for (const name of [alias, alias.toUpperCase()]) {
const streaming = createHash(name, options).update(input).digest('hex');
assert.strictEqual(streaming, expected);
assert.strictEqual(hash(name, input, options), expected);
}
}
}
// These digests are tested when the active provider advertises them.
for (const name of ['keccak-kmac-128', 'keccak-256', 'sha256-192']) {
const vector = providerVectors[name];
if (vector.aliases.some((alias) => hashes.includes(alias))) {
testHashVector(vector);
} else {
common.printSkipMessage(`${name} is not available from the active provider`);
}
}
const keccakKmacName = providerVectors['keccak-kmac-128'].aliases
.find((alias) => hashes.includes(alias));
if (keccakKmacName !== undefined) {
(async () => {
const { expected } = providerVectors['keccak-kmac-128'];
const { 0: err, 1: syncResult } = new HashJob(
kCryptoJobSync,
keccakKmacName,
input,
256,
).run();
assert.strictEqual(err, undefined);
assert.strictEqual(Buffer.from(syncResult).toString('hex'), expected);
const result = await new HashJob(
kCryptoJobWebCrypto,
keccakKmacName,
input,
256,
).run();
assert.strictEqual(Buffer.from(result).toString('hex'), expected);
})().then(common.mustCall());
}
if (hashes.includes('sha256-192')) {
const operationInput = Buffer.from('abc');
assert.strictEqual(
createHmac('sha256-192', 'key').update(operationInput).digest('hex'),
'd7774e586190fa2d2f4d4be4bc86ccd459a9170d52c38809',
);
const hkdfExpected = 'ef23757b94b5e1e46c3f981d87828d7aeb0207733ab5c78' +
'c60df321c9e8c88e0ad54b4eecfef8c258ccd';
assert.strictEqual(
Buffer.from(hkdfSync('sha256-192', 'key', 'salt', 'info', 42))
.toString('hex'),
hkdfExpected,
);
hkdf(
'sha256-192',
'key',
'salt',
'info',
42,
common.mustSucceed((result) => {
assert.strictEqual(Buffer.from(result).toString('hex'), hkdfExpected);
}),
);
const pbkdf2Expected = '1fee3dd5ea13d5b563d3cc88fbc6dcf7' +
'3497aeffc3b3e6358ab3d3d1aa2aa0ee';
assert.strictEqual(
pbkdf2Sync('password', 'salt', 2, 32, 'sha256-192').toString('hex'),
pbkdf2Expected,
);
pbkdf2(
'password',
'salt',
2,
32,
'sha256-192',
common.mustSucceed((result) => {
assert.strictEqual(result.toString('hex'), pbkdf2Expected);
}),
);
const { privateKey: ecPrivateKey, publicKey: ecPublicKey } =
generateKeyPairSync('ec', { namedCurve: 'prime256v1' });
const signature = sign('sha256-192', operationInput, ecPrivateKey);
assert(verify('sha256-192', operationInput, ecPublicKey, signature));
const streamingSignature = createSign('sha256-192')
.update(operationInput)
.sign(ecPrivateKey);
const verifier = createVerify('sha256-192');
verifier.update(operationInput);
assert(verifier.verify(ecPublicKey, streamingSignature));
sign(
'sha256-192',
operationInput,
ecPrivateKey,
common.mustSucceed((asyncSignature) => {
verify(
'sha256-192',
operationInput,
ecPublicKey,
asyncSignature,
common.mustSucceed((result) => assert(result)),
);
}),
);
const { privateKey: rsaPrivateKey, publicKey: rsaPublicKey } =
generateKeyPairSync('rsa', { modulusLength: 2048 });
const plaintext = Buffer.from('provider digest');
assert.throws(
() => sign('sha256-192', plaintext, rsaPrivateKey),
{ code: 'ERR_OSSL_DIGEST_NOT_ALLOWED' },
);
assert.deepStrictEqual(
privateDecrypt(
{ key: rsaPrivateKey, oaepHash: 'sha256-192' },
publicEncrypt(
{ key: rsaPublicKey, oaepHash: 'sha256-192' },
plaintext,
),
),
plaintext,
);
const pssOptions = [
{
hashAlgorithm: 'sha256-192',
modulusLength: 2048,
},
{
hashAlgorithm: 'sha256',
mgf1HashAlgorithm: 'sha256-192',
modulusLength: 2048,
},
];
const keyGenerationFailed = { message: 'Key generation job failed' };
for (const options of pssOptions) {
assert.throws(
() => generateKeyPairSync('rsa-pss', options),
keyGenerationFailed,
);
generateKeyPair(
'rsa-pss',
options,
common.mustCall((err, publicKey, privateKey) => {
assert.strictEqual(err?.message, keyGenerationFailed.message);
assert.strictEqual(publicKey, undefined);
assert.strictEqual(privateKey, undefined);
}),
);
}
}
+10 -1
View File
@@ -1,6 +1,8 @@
declare namespace InternalCryptoBinding {
type Buffer = Uint8Array;
type ByteSource = string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView;
type BufferSource = ArrayBuffer | SharedArrayBuffer | ArrayBufferView;
type OptionalBufferSource = BufferSource | undefined;
type ByteSource = string | BufferSource;
type OptionalByteSource = ByteSource | undefined;
type JwkKey = Record<string, string | string[] | boolean | undefined>;
type KeyFormatDER = 0;
@@ -300,6 +302,8 @@ declare namespace InternalCryptoBinding {
algorithm: string,
data: ByteSource,
outputLength?: number,
functionName?: OptionalBufferSource,
customization?: OptionalBufferSource,
): CryptoJobForMode<M, ArrayBuffer>;
}
@@ -818,6 +822,8 @@ export interface CryptoBinding {
xofLen?: number,
algorithmId?: number,
algorithmCache?: Record<string, number>,
functionName?: InternalCryptoBinding.OptionalBufferSource,
customization?: InternalCryptoBinding.OptionalBufferSource,
) => InternalCryptoBinding.HashHandle;
Hmac: new () => InternalCryptoBinding.HmacHandle;
KeyObjectHandle: new () => InternalCryptoBinding.KeyObjectHandle;
@@ -939,6 +945,7 @@ export interface CryptoBinding {
getCurves(): string[];
getExtraCACertificates(): string[];
getFipsCrypto(): 0 | 1;
getFipsCryptoGeneration(): bigint;
getHashes(): string[];
getKeyObjectSlots(key: object): InternalCryptoBinding.KeyObjectSlots;
getOpenSSLSecLevelCrypto(): number | undefined;
@@ -953,6 +960,8 @@ export interface CryptoBinding {
outputEncoding: string,
outputEncodingId?: number,
outputLength?: number,
functionName?: InternalCryptoBinding.OptionalBufferSource,
customization?: InternalCryptoBinding.OptionalBufferSource,
): string | InternalCryptoBinding.Buffer;
parseX509(data: InternalCryptoBinding.ByteSource): InternalCryptoBinding.X509CertificateHandle;
privateDecrypt: InternalCryptoBinding.PublicKeyCipher;