Skip to content

crypto: add optional callback to crypto.diffieHellman #57274

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 15, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions doc/api/crypto.md
Original file line number Diff line number Diff line change
Expand Up @@ -3533,23 +3533,32 @@ the corresponding digest algorithm. This does not work for all signature
algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest
algorithm names.

### `crypto.diffieHellman(options)`
### `crypto.diffieHellman(options[, callback])`

<!-- YAML
added:
- v13.9.0
- v12.17.0
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/57274
description: Optional callback argument added.
-->

* `options`: {Object}
* `privateKey`: {KeyObject}
* `publicKey`: {KeyObject}
* Returns: {Buffer}
* `callback` {Function}
* `err` {Error}
* `secret` {Buffer}
* Returns: {Buffer} if the `callback` function is not provided.

Computes the Diffie-Hellman secret based on a `privateKey` and a `publicKey`.
Both keys must have the same `asymmetricKeyType`, which must be one of `'dh'`
(for Diffie-Hellman), `'ec'`, `'x448'`, or `'x25519'` (for ECDH).

If the `callback` function is provided this function uses libuv's threadpool.

### `crypto.fips`

<!-- YAML
Expand Down
29 changes: 26 additions & 3 deletions lib/internal/crypto/diffiehellman.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

const {
ArrayBufferPrototypeSlice,
FunctionPrototypeCall,
MathCeil,
ObjectDefineProperty,
SafeSet,
Expand All @@ -11,13 +12,14 @@ const {
const { Buffer } = require('buffer');

const {
DHBitsJob,
DiffieHellman: _DiffieHellman,
DiffieHellmanGroup: _DiffieHellmanGroup,
ECDH: _ECDH,
ECDHBitsJob,
ECDHConvertKey: _ECDHConvertKey,
statelessDH,
kCryptoJobAsync,
kCryptoJobSync,
} = internalBinding('crypto');

const {
Expand All @@ -32,6 +34,7 @@ const {
} = require('internal/errors');

const {
validateFunction,
validateInt32,
validateObject,
validateString,
Expand Down Expand Up @@ -268,9 +271,12 @@ function getFormat(format) {

const dhEnabledKeyTypes = new SafeSet(['dh', 'ec', 'x448', 'x25519']);

function diffieHellman(options) {
function diffieHellman(options, callback) {
validateObject(options, 'options');

if (callback !== undefined)
validateFunction(callback, 'callback');

const { privateKey, publicKey } = options;
if (!(privateKey instanceof KeyObject))
throw new ERR_INVALID_ARG_VALUE('options.privateKey', privateKey);
Expand All @@ -293,7 +299,24 @@ function diffieHellman(options) {
`${privateType} and ${publicType}`);
}

return statelessDH(privateKey[kHandle], publicKey[kHandle]);
const job = new DHBitsJob(
callback ? kCryptoJobAsync : kCryptoJobSync,
publicKey[kHandle],
privateKey[kHandle]);

if (!callback) {
const { 0: err, 1: secret } = job.run();
if (err !== undefined)
throw err;

return Buffer.from(secret);
}

job.ondone = (error, secret) => {
if (error) return FunctionPrototypeCall(callback, job, error);
FunctionPrototypeCall(callback, job, null, Buffer.from(secret));
};
job.run();
}

let masks;
Expand Down
63 changes: 16 additions & 47 deletions src/crypto/crypto_dh.cc
Original file line number Diff line number Diff line change
Expand Up @@ -483,49 +483,11 @@ WebCryptoKeyExportStatus DHKeyExportTraits::DoExport(
}
}

namespace {
ByteSource StatelessDiffieHellmanThreadsafe(const EVPKeyPointer& our_key,
const EVPKeyPointer& their_key) {
auto dp = DHPointer::stateless(our_key, their_key);
if (!dp) return {};
DCHECK(!dp.isSecure());

return ByteSource::Allocated(dp.release());
}

void Stateless(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);

CHECK(args[0]->IsObject() && args[1]->IsObject());
KeyObjectHandle* our_key_object;
ASSIGN_OR_RETURN_UNWRAP(&our_key_object, args[0].As<Object>());
CHECK_EQ(our_key_object->Data().GetKeyType(), kKeyTypePrivate);
KeyObjectHandle* their_key_object;
ASSIGN_OR_RETURN_UNWRAP(&their_key_object, args[1].As<Object>());
CHECK_NE(their_key_object->Data().GetKeyType(), kKeyTypeSecret);

const auto& our_key = our_key_object->Data().GetAsymmetricKey();
const auto& their_key = their_key_object->Data().GetAsymmetricKey();

Local<Value> out;
if (!StatelessDiffieHellmanThreadsafe(our_key, their_key)
.ToBuffer(env)
.ToLocal(&out)) return;

if (Buffer::Length(out) == 0)
return ThrowCryptoError(env, ERR_get_error(), "diffieHellman failed");

args.GetReturnValue().Set(out);
}
} // namespace

Maybe<void> DHBitsTraits::AdditionalConfig(
CryptoJobMode mode,
const FunctionCallbackInfo<Value>& args,
unsigned int offset,
DHBitsConfig* params) {
Environment* env = Environment::GetCurrent(args);

CHECK(args[offset]->IsObject()); // public key
CHECK(args[offset + 1]->IsObject()); // private key

Expand All @@ -535,11 +497,8 @@ Maybe<void> DHBitsTraits::AdditionalConfig(
ASSIGN_OR_RETURN_UNWRAP(&public_key, args[offset], Nothing<void>());
ASSIGN_OR_RETURN_UNWRAP(&private_key, args[offset + 1], Nothing<void>());

if (private_key->Data().GetKeyType() != kKeyTypePrivate ||
public_key->Data().GetKeyType() != kKeyTypePublic) {
THROW_ERR_CRYPTO_INVALID_KEYTYPE(env);
return Nothing<void>();
}
CHECK(private_key->Data().GetKeyType() == kKeyTypePrivate);
CHECK(public_key->Data().GetKeyType() != kKeyTypeSecret);

params->public_key = public_key->Data().addRef();
params->private_key = private_key->Data().addRef();
Expand All @@ -557,8 +516,20 @@ bool DHBitsTraits::DeriveBits(
Environment* env,
const DHBitsConfig& params,
ByteSource* out) {
*out = StatelessDiffieHellmanThreadsafe(params.private_key.GetAsymmetricKey(),
params.public_key.GetAsymmetricKey());
auto dp = DHPointer::stateless(params.private_key.GetAsymmetricKey(),
params.public_key.GetAsymmetricKey());
if (!dp) {
bool can_throw =
per_process::v8_initialized && Isolate::TryGetCurrent() != nullptr;
if (can_throw) {
unsigned long err = ERR_get_error(); // NOLINT(runtime/int)
if (err) ThrowCryptoError(env, err, "diffieHellman failed");
}
return false;
}

*out = ByteSource::Allocated(dp.release());
CHECK(!out->empty());
return true;
}

Expand Down Expand Up @@ -611,7 +582,6 @@ void DiffieHellman::Initialize(Environment* env, Local<Object> target) {
make(FIXED_ONE_BYTE_STRING(env->isolate(), "DiffieHellmanGroup"),
DiffieHellmanGroup);

SetMethodNoSideEffect(context, target, "statelessDH", Stateless);
DHKeyPairGenJob::Initialize(env, target);
DHKeyExportJob::Initialize(env, target);
DHBitsJob::Initialize(env, target);
Expand All @@ -632,7 +602,6 @@ void DiffieHellman::RegisterExternalReferences(
registry->Register(SetPrivateKey);

registry->Register(Check);
registry->Register(Stateless);

DHKeyPairGenJob::RegisterExternalReferences(registry);
DHKeyExportJob::RegisterExternalReferences(registry);
Expand Down
Loading
Loading