Commit 4afc15b

Browse files
panvaaduh95
authored andcommitted
src: avoid redundant KEM encapsulation copies
KEM encapsulation produces separate ciphertext and shared-secret allocations. The existing DeriveBitsJob path packs both values into an intermediate buffer, then copies them again into separate buffers. Instead, this uses a dedicated KEMEncapsulateJob to retain both outputs across the worker boundary and convert each directly through ByteSource. This removes the intermediate allocation and at least one complete round of copies. Signed-off-by: Filip Skokan <panva.ip@gmail.com> PR-URL: #64553 Backport-PR-URL: #65087 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com> Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
1 parent fea0666 commit 4afc15b

2 files changed

Lines changed: 116 additions & 104 deletions

File tree

β€Žsrc/crypto/crypto_kem.ccβ€Ž

Lines changed: 94 additions & 96 deletions
Original file line numberDiff line numberDiff line change
@@ -8,21 +8,20 @@
88
#include"crypto/crypto_util.h"
99
#include"env-inl.h"
1010
#include"memory_tracker-inl.h"
11-
#include"node_buffer.h"
1211
#include"threadpoolwork-inl.h"
1312
#include"v8.h"
1413

1514
namespacenode {
1615

1716
using ncrypto::EVPKeyPointer;
1817
using v8::Array;
19-
using v8::ArrayBufferView;
2018
using v8::FunctionCallbackInfo;
2119
using v8::Local;
2220
using v8::Maybe;
2321
using v8::MaybeLocal;
2422
using v8::Nothing;
2523
using v8::Object;
24+
using v8::Uint8Array;
2625
using v8::Value;
2726

2827
namespacecrypto {
@@ -49,51 +48,6 @@ void KEMConfiguration::MemoryInfo(MemoryTracker* tracker) const {
4948

5049
namespace {
5150

52-
boolDoKEMEncapsulate(Environment* env,
53-
const EVPKeyPointer& public_key,
54-
ByteSource* out,
55-
CryptoJobMode mode) {
56-
auto result = ncrypto::KEM::Encapsulate(public_key);
57-
if (!result) {
58-
if (mode == kCryptoJobSync) {
59-
THROW_ERR_CRYPTO_OPERATION_FAILED(env, "Failed to perform encapsulation");
60-
}
61-
returnfalse;
62-
}
63-
64-
// Pack the result: [ciphertext_len][shared_key_len][ciphertext][shared_key]
65-
size_t ciphertext_len = result->ciphertext.size();
66-
size_t shared_key_len = result->shared_key.size();
67-
size_t total_len =
68-
sizeof(uint32_t) + sizeof(uint32_t) + ciphertext_len + shared_key_len;
69-
70-
auto data = ncrypto::DataPointer::Alloc(total_len);
71-
if (!data) {
72-
if (mode == kCryptoJobSync) {
73-
THROW_ERR_CRYPTO_OPERATION_FAILED(env,
74-
"Failed to allocate output buffer");
75-
}
76-
returnfalse;
77-
}
78-
79-
unsignedchar* ptr = static_cast<unsignedchar*>(data.get());
80-
81-
// Write size headers
82-
*reinterpret_cast<uint32_t*>(ptr) = static_cast<uint32_t>(ciphertext_len);
83-
*reinterpret_cast<uint32_t*>(ptr + sizeof(uint32_t)) =
84-
static_cast<uint32_t>(shared_key_len);
85-
86-
// Write ciphertext and shared key data
87-
unsignedchar* ciphertext_ptr = ptr + 2 * sizeof(uint32_t);
88-
unsignedchar* shared_key_ptr = ciphertext_ptr + ciphertext_len;
89-
90-
std::memcpy(ciphertext_ptr, result->ciphertext.get(), ciphertext_len);
91-
std::memcpy(shared_key_ptr, result->shared_key.get(), shared_key_len);
92-
93-
*out = ByteSource::Allocated(data.release());
94-
returntrue;
95-
}
96-
9751
boolDoKEMDecapsulate(Environment* env,
9852
const EVPKeyPointer& private_key,
9953
const ByteSource& ciphertext,
@@ -135,71 +89,115 @@ Maybe<void> KEMEncapsulateTraits::AdditionalConfig(
13589
returnv8::JustVoid();
13690
}
13791

138-
boolKEMEncapsulateTraits::DeriveBits(Environment* env,
139-
const KEMConfiguration& params,
140-
ByteSource* out,
141-
CryptoJobMode mode) {
142-
Mutex::ScopedLock lock(params.key.mutex());
143-
constauto& public_key = params.key.GetAsymmetricKey();
92+
voidKEMEncapsulateJob::New(const FunctionCallbackInfo<Value>& args) {
93+
Environment* env = Environment::GetCurrent(args);
94+
CHECK(args.IsConstructCall());
95+
96+
CryptoJobMode mode = GetCryptoJobMode(args[0]);
97+
AdditionalParams params;
98+
if (KEMEncapsulateTraits::AdditionalConfig(mode, args, 1, &params)
99+
.IsNothing()) {
100+
return;
101+
}
144102

145-
returnDoKEMEncapsulate(env, public_key, out, mode);
103+
newKEMEncapsulateJob(env, args.This(), mode, std::move(params));
146104
}
147105

148-
MaybeLocal<Value> KEMEncapsulateTraits::EncodeOutput(
149-
Environment* env, const KEMConfiguration& params, ByteSource* out) {
150-
// The output contains:
151-
// [ciphertext_len][shared_key_len][ciphertext][shared_key]
152-
constunsignedchar* data = out->data<unsignedchar>();
153-
154-
uint32_t ciphertext_len = *reinterpret_cast<constuint32_t*>(data);
155-
uint32_t shared_key_len =
156-
*reinterpret_cast<constuint32_t*>(data + sizeof(uint32_t));
157-
158-
constunsignedchar* ciphertext_ptr = data + 2 * sizeof(uint32_t);
159-
constunsignedchar* shared_key_ptr = ciphertext_ptr + ciphertext_len;
160-
161-
MaybeLocal<Object> ciphertext_buf =
162-
node::Buffer::Copy(env->isolate(),
163-
reinterpret_cast<constchar*>(ciphertext_ptr),
164-
ciphertext_len);
165-
166-
MaybeLocal<Object> shared_key_buf =
167-
node::Buffer::Copy(env->isolate(),
168-
reinterpret_cast<constchar*>(shared_key_ptr),
169-
shared_key_len);
170-
171-
Local<Object> ciphertext_obj;
172-
Local<Object> shared_key_obj;
173-
if (!ciphertext_buf.ToLocal(&ciphertext_obj) ||
174-
!shared_key_buf.ToLocal(&shared_key_obj)) {
175-
return MaybeLocal<Value>();
106+
voidKEMEncapsulateJob::Initialize(Environment* env, Local<Object> target) {
107+
CryptoJob<KEMEncapsulateTraits>::Initialize(New, env, target);
108+
}
109+
110+
voidKEMEncapsulateJob::RegisterExternalReferences(
111+
ExternalReferenceRegistry* registry) {
112+
CryptoJob<KEMEncapsulateTraits>::RegisterExternalReferences(New, registry);
113+
}
114+
115+
KEMEncapsulateJob::KEMEncapsulateJob(Environment* env,
116+
Local<Object> object,
117+
CryptoJobMode mode,
118+
AdditionalParams&& params)
119+
: CryptoJob<KEMEncapsulateTraits>(env,
120+
object,
121+
KEMEncapsulateTraits::Provider,
122+
mode,
123+
std::move(params)) {}
124+
125+
voidKEMEncapsulateJob::DoThreadPoolWork() {
126+
ncrypto::ClearErrorOnReturn clear_error_on_return;
127+
AdditionalParams* params = CryptoJob<KEMEncapsulateTraits>::params();
128+
Mutex::ScopedLock lock(params->key.mutex());
129+
out_ = ncrypto::KEM::Encapsulate(params->key.GetAsymmetricKey());
130+
if (!out_) {
131+
if (mode() == kCryptoJobSync) {
132+
THROW_ERR_CRYPTO_OPERATION_FAILED(AsyncWrap::env(),
133+
"Failed to perform encapsulation");
134+
}
135+
CryptoErrorStore* errors = CryptoJob<KEMEncapsulateTraits>::errors();
136+
errors->Capture();
137+
if (errors->Empty()) {
138+
errors->Insert(NodeCryptoError::DERIVING_BITS_FAILED);
139+
}
176140
}
141+
}
177142

178-
if (params.job_mode == kCryptoJobWebCrypto) {
179-
Local<Object> result = Object::New(env->isolate());
180-
if (!result
143+
Maybe<void> KEMEncapsulateJob::ToResult(Local<Value>* err,
144+
Local<Value>* result) {
145+
Environment* env = AsyncWrap::env();
146+
CryptoErrorStore* errors = CryptoJob<KEMEncapsulateTraits>::errors();
147+
if (!out_) {
148+
if (errors->Empty()) errors->Capture();
149+
CHECK(!errors->Empty());
150+
*result = v8::Undefined(env->isolate());
151+
if (!errors->ToException(env).ToLocal(err)) return Nothing<void>();
152+
returnv8::JustVoid();
153+
}
154+
155+
CHECK(errors->Empty());
156+
*err = v8::Undefined(env->isolate());
157+
158+
ByteSource ciphertext = ByteSource::Allocated(out_->ciphertext.release());
159+
ByteSource shared_key = ByteSource::Allocated(out_->shared_key.release());
160+
161+
if (mode() == kCryptoJobWebCrypto) {
162+
Local<Object> output = Object::New(env->isolate());
163+
if (!output
181164
->DefineOwnProperty(env->context(),
182165
OneByteString(env->isolate(), "sharedKey"),
183-
shared_key_obj.As<ArrayBufferView>()->Buffer())
166+
shared_key.ToArrayBuffer(env))
184167
.FromMaybe(false) ||
185-
!result
168+
!output
186169
->DefineOwnProperty(env->context(),
187170
OneByteString(env->isolate(), "ciphertext"),
188-
ciphertext_obj.As<ArrayBufferView>()->Buffer())
171+
ciphertext.ToArrayBuffer(env))
189172
.FromMaybe(false)) {
190-
returnMaybeLocal<Value>();
173+
returnNothing<void>();
191174
}
192-
return result;
175+
*result = output;
176+
returnv8::JustVoid();
193177
}
194178

195-
// Return an array [sharedKey, ciphertext].
196-
Local<Array> result = Array::New(env->isolate(), 2);
197-
if (result->Set(env->context(), 0, shared_key_obj).IsNothing() ||
198-
result->Set(env->context(), 1, ciphertext_obj).IsNothing()) {
199-
returnMaybeLocal<Value>();
179+
Local<Uint8Array> shared_key_buf;
180+
Local<Uint8Array> ciphertext_buf;
181+
if (!shared_key.ToBuffer(env).ToLocal(&shared_key_buf) ||
182+
!ciphertext.ToBuffer(env).ToLocal(&ciphertext_buf)) {
183+
returnNothing<void>();
200184
}
201185

202-
return result;
186+
Local<Array> output = Array::New(env->isolate(), 2);
187+
if (output->Set(env->context(), 0, shared_key_buf).IsNothing() ||
188+
output->Set(env->context(), 1, ciphertext_buf).IsNothing()) {
189+
return Nothing<void>();
190+
}
191+
*result = output;
192+
returnv8::JustVoid();
193+
}
194+
195+
voidKEMEncapsulateJob::MemoryInfo(MemoryTracker* tracker) const {
196+
if (out_) {
197+
tracker->TrackFieldWithSize("ciphertext", out_->ciphertext.size());
198+
tracker->TrackFieldWithSize("shared_key", out_->shared_key.size());
199+
}
200+
CryptoJob<KEMEncapsulateTraits>::MemoryInfo(tracker);
203201
}
204202

205203
// KEMDecapsulateTraits implementation

β€Žsrc/crypto/crypto_kem.hβ€Ž

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -44,15 +44,30 @@ struct KEMEncapsulateTraits final {
4444
const v8::FunctionCallbackInfo<v8::Value>& args,
4545
unsignedint offset,
4646
KEMConfiguration* params);
47+
};
4748

48-
staticboolDeriveBits(Environment* env,
49-
const KEMConfiguration& params,
50-
ByteSource* out,
51-
CryptoJobMode mode);
49+
classKEMEncapsulateJobfinal : public CryptoJob<KEMEncapsulateTraits> {
50+
public:
51+
using AdditionalParams = KEMEncapsulateTraits::AdditionalParameters;
5252

53-
static v8::MaybeLocal<v8::Value> EncodeOutput(Environment* env,
54-
const KEMConfiguration& params,
55-
ByteSource* out);
53+
staticvoidNew(const v8::FunctionCallbackInfo<v8::Value>& args);
54+
staticvoidInitialize(Environment* env, v8::Local<v8::Object> target);
55+
staticvoidRegisterExternalReferences(ExternalReferenceRegistry* registry);
56+
57+
KEMEncapsulateJob(Environment* env,
58+
v8::Local<v8::Object> object,
59+
CryptoJobMode mode,
60+
AdditionalParams&& params);
61+
62+
voidDoThreadPoolWork() override;
63+
v8::Maybe<void> ToResult(v8::Local<v8::Value>* err,
64+
v8::Local<v8::Value>* result) override;
65+
66+
SET_SELF_SIZE(KEMEncapsulateJob)
67+
voidMemoryInfo(MemoryTracker* tracker) constoverride;
68+
69+
private:
70+
std::optional<ncrypto::KEM::EncapsulateResult> out_;
5671
};
5772

5873
structKEMDecapsulateTraitsfinal {
@@ -78,7 +93,6 @@ struct KEMDecapsulateTraits final {
7893
ByteSource* out);
7994
};
8095

81-
using KEMEncapsulateJob = DeriveBitsJob<KEMEncapsulateTraits>;
8296
using KEMDecapsulateJob = DeriveBitsJob<KEMDecapsulateTraits>;
8397

8498
voidInitializeKEM(Environment* env, v8::Local<v8::Object> target);

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Commit 4afc15b

Browse files
panvaaduh95
authored andcommitted
src: avoid redundant KEM encapsulation copies
KEM encapsulation produces separate ciphertext and shared-secret allocations. The existing DeriveBitsJob path packs both values into an intermediate buffer, then copies them again into separate buffers. Instead, this uses a dedicated KEMEncapsulateJob to retain both outputs across the worker boundary and convert each directly through ByteSource. This removes the intermediate allocation and at least one complete round of copies. Signed-off-by: Filip Skokan <panva.ip@gmail.com> PR-URL: #64553 Backport-PR-URL: #65087 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com> Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
1 parent fea0666 commit 4afc15b

2 files changed

Lines changed: 116 additions & 104 deletions

File tree

β€Žsrc/crypto/crypto_kem.ccβ€Ž

Lines changed: 94 additions & 96 deletions
Original file line numberDiff line numberDiff line change
@@ -8,21 +8,20 @@
88
#include"crypto/crypto_util.h"
99
#include"env-inl.h"
1010
#include"memory_tracker-inl.h"
11-
#include"node_buffer.h"
1211
#include"threadpoolwork-inl.h"
1312
#include"v8.h"
1413

1514
namespacenode {
1615

1716
using ncrypto::EVPKeyPointer;
1817
using v8::Array;
19-
using v8::ArrayBufferView;
2018
using v8::FunctionCallbackInfo;
2119
using v8::Local;
2220
using v8::Maybe;
2321
using v8::MaybeLocal;
2422
using v8::Nothing;
2523
using v8::Object;
24+
using v8::Uint8Array;
2625
using v8::Value;
2726

2827
namespacecrypto {
@@ -49,51 +48,6 @@ void KEMConfiguration::MemoryInfo(MemoryTracker* tracker) const {
4948

5049
namespace {
5150

52-
boolDoKEMEncapsulate(Environment* env,
53-
const EVPKeyPointer& public_key,
54-
ByteSource* out,
55-
CryptoJobMode mode) {
56-
auto result = ncrypto::KEM::Encapsulate(public_key);
57-
if (!result) {
58-
if (mode == kCryptoJobSync) {
59-
THROW_ERR_CRYPTO_OPERATION_FAILED(env, "Failed to perform encapsulation");
60-
}
61-
returnfalse;
62-
}
63-
64-
// Pack the result: [ciphertext_len][shared_key_len][ciphertext][shared_key]
65-
size_t ciphertext_len = result->ciphertext.size();
66-
size_t shared_key_len = result->shared_key.size();
67-
size_t total_len =
68-
sizeof(uint32_t) + sizeof(uint32_t) + ciphertext_len + shared_key_len;
69-
70-
auto data = ncrypto::DataPointer::Alloc(total_len);
71-
if (!data) {
72-
if (mode == kCryptoJobSync) {
73-
THROW_ERR_CRYPTO_OPERATION_FAILED(env,
74-
"Failed to allocate output buffer");
75-
}
76-
returnfalse;
77-
}
78-
79-
unsignedchar* ptr = static_cast<unsignedchar*>(data.get());
80-
81-
// Write size headers
82-
*reinterpret_cast<uint32_t*>(ptr) = static_cast<uint32_t>(ciphertext_len);
83-
*reinterpret_cast<uint32_t*>(ptr + sizeof(uint32_t)) =
84-
static_cast<uint32_t>(shared_key_len);
85-
86-
// Write ciphertext and shared key data
87-
unsignedchar* ciphertext_ptr = ptr + 2 * sizeof(uint32_t);
88-
unsignedchar* shared_key_ptr = ciphertext_ptr + ciphertext_len;
89-
90-
std::memcpy(ciphertext_ptr, result->ciphertext.get(), ciphertext_len);
91-
std::memcpy(shared_key_ptr, result->shared_key.get(), shared_key_len);
92-
93-
*out = ByteSource::Allocated(data.release());
94-
returntrue;
95-
}
96-
9751
boolDoKEMDecapsulate(Environment* env,
9852
const EVPKeyPointer& private_key,
9953
const ByteSource& ciphertext,
@@ -135,71 +89,115 @@ Maybe<void> KEMEncapsulateTraits::AdditionalConfig(
13589
returnv8::JustVoid();
13690
}
13791

138-
boolKEMEncapsulateTraits::DeriveBits(Environment* env,
139-
const KEMConfiguration& params,
140-
ByteSource* out,
141-
CryptoJobMode mode) {
142-
Mutex::ScopedLock lock(params.key.mutex());
143-
constauto& public_key = params.key.GetAsymmetricKey();
92+
voidKEMEncapsulateJob::New(const FunctionCallbackInfo<Value>& args) {
93+
Environment* env = Environment::GetCurrent(args);
94+
CHECK(args.IsConstructCall());
95+
96+
CryptoJobMode mode = GetCryptoJobMode(args[0]);
97+
AdditionalParams params;
98+
if (KEMEncapsulateTraits::AdditionalConfig(mode, args, 1, &params)
99+
.IsNothing()) {
100+
return;
101+
}
144102

145-
returnDoKEMEncapsulate(env, public_key, out, mode);
103+
newKEMEncapsulateJob(env, args.This(), mode, std::move(params));
146104
}
147105

148-
MaybeLocal<Value> KEMEncapsulateTraits::EncodeOutput(
149-
Environment* env, const KEMConfiguration& params, ByteSource* out) {
150-
// The output contains:
151-
// [ciphertext_len][shared_key_len][ciphertext][shared_key]
152-
constunsignedchar* data = out->data<unsignedchar>();
153-
154-
uint32_t ciphertext_len = *reinterpret_cast<constuint32_t*>(data);
155-
uint32_t shared_key_len =
156-
*reinterpret_cast<constuint32_t*>(data + sizeof(uint32_t));
157-
158-
constunsignedchar* ciphertext_ptr = data + 2 * sizeof(uint32_t);
159-
constunsignedchar* shared_key_ptr = ciphertext_ptr + ciphertext_len;
160-
161-
MaybeLocal<Object> ciphertext_buf =
162-
node::Buffer::Copy(env->isolate(),
163-
reinterpret_cast<constchar*>(ciphertext_ptr),
164-
ciphertext_len);
165-
166-
MaybeLocal<Object> shared_key_buf =
167-
node::Buffer::Copy(env->isolate(),
168-
reinterpret_cast<constchar*>(shared_key_ptr),
169-
shared_key_len);
170-
171-
Local<Object> ciphertext_obj;
172-
Local<Object> shared_key_obj;
173-
if (!ciphertext_buf.ToLocal(&ciphertext_obj) ||
174-
!shared_key_buf.ToLocal(&shared_key_obj)) {
175-
return MaybeLocal<Value>();
106+
voidKEMEncapsulateJob::Initialize(Environment* env, Local<Object> target) {
107+
CryptoJob<KEMEncapsulateTraits>::Initialize(New, env, target);
108+
}
109+
110+
voidKEMEncapsulateJob::RegisterExternalReferences(
111+
ExternalReferenceRegistry* registry) {
112+
CryptoJob<KEMEncapsulateTraits>::RegisterExternalReferences(New, registry);
113+
}
114+
115+
KEMEncapsulateJob::KEMEncapsulateJob(Environment* env,
116+
Local<Object> object,
117+
CryptoJobMode mode,
118+
AdditionalParams&& params)
119+
: CryptoJob<KEMEncapsulateTraits>(env,
120+
object,
121+
KEMEncapsulateTraits::Provider,
122+
mode,
123+
std::move(params)) {}
124+
125+
voidKEMEncapsulateJob::DoThreadPoolWork() {
126+
ncrypto::ClearErrorOnReturn clear_error_on_return;
127+
AdditionalParams* params = CryptoJob<KEMEncapsulateTraits>::params();
128+
Mutex::ScopedLock lock(params->key.mutex());
129+
out_ = ncrypto::KEM::Encapsulate(params->key.GetAsymmetricKey());
130+
if (!out_) {
131+
if (mode() == kCryptoJobSync) {
132+
THROW_ERR_CRYPTO_OPERATION_FAILED(AsyncWrap::env(),
133+
"Failed to perform encapsulation");
134+
}
135+
CryptoErrorStore* errors = CryptoJob<KEMEncapsulateTraits>::errors();
136+
errors->Capture();
137+
if (errors->Empty()) {
138+
errors->Insert(NodeCryptoError::DERIVING_BITS_FAILED);
139+
}
176140
}
141+
}
177142

178-
if (params.job_mode == kCryptoJobWebCrypto) {
179-
Local<Object> result = Object::New(env->isolate());
180-
if (!result
143+
Maybe<void> KEMEncapsulateJob::ToResult(Local<Value>* err,
144+
Local<Value>* result) {
145+
Environment* env = AsyncWrap::env();
146+
CryptoErrorStore* errors = CryptoJob<KEMEncapsulateTraits>::errors();
147+
if (!out_) {
148+
if (errors->Empty()) errors->Capture();
149+
CHECK(!errors->Empty());
150+
*result = v8::Undefined(env->isolate());
151+
if (!errors->ToException(env).ToLocal(err)) return Nothing<void>();
152+
returnv8::JustVoid();
153+
}
154+
155+
CHECK(errors->Empty());
156+
*err = v8::Undefined(env->isolate());
157+
158+
ByteSource ciphertext = ByteSource::Allocated(out_->ciphertext.release());
159+
ByteSource shared_key = ByteSource::Allocated(out_->shared_key.release());
160+
161+
if (mode() == kCryptoJobWebCrypto) {
162+
Local<Object> output = Object::New(env->isolate());
163+
if (!output
181164
->DefineOwnProperty(env->context(),
182165
OneByteString(env->isolate(), "sharedKey"),
183-
shared_key_obj.As<ArrayBufferView>()->Buffer())
166+
shared_key.ToArrayBuffer(env))
184167
.FromMaybe(false) ||
185-
!result
168+
!output
186169
->DefineOwnProperty(env->context(),
187170
OneByteString(env->isolate(), "ciphertext"),
188-
ciphertext_obj.As<ArrayBufferView>()->Buffer())
171+
ciphertext.ToArrayBuffer(env))
189172
.FromMaybe(false)) {
190-
returnMaybeLocal<Value>();
173+
returnNothing<void>();
191174
}
192-
return result;
175+
*result = output;
176+
returnv8::JustVoid();
193177
}
194178

195-
// Return an array [sharedKey, ciphertext].
196-
Local<Array> result = Array::New(env->isolate(), 2);
197-
if (result->Set(env->context(), 0, shared_key_obj).IsNothing() ||
198-
result->Set(env->context(), 1, ciphertext_obj).IsNothing()) {
199-
returnMaybeLocal<Value>();
179+
Local<Uint8Array> shared_key_buf;
180+
Local<Uint8Array> ciphertext_buf;
181+
if (!shared_key.ToBuffer(env).ToLocal(&shared_key_buf) ||
182+
!ciphertext.ToBuffer(env).ToLocal(&ciphertext_buf)) {
183+
returnNothing<void>();
200184
}
201185

202-
return result;
186+
Local<Array> output = Array::New(env->isolate(), 2);
187+
if (output->Set(env->context(), 0, shared_key_buf).IsNothing() ||
188+
output->Set(env->context(), 1, ciphertext_buf).IsNothing()) {
189+
return Nothing<void>();
190+
}
191+
*result = output;
192+
returnv8::JustVoid();
193+
}
194+
195+
voidKEMEncapsulateJob::MemoryInfo(MemoryTracker* tracker) const {
196+
if (out_) {
197+
tracker->TrackFieldWithSize("ciphertext", out_->ciphertext.size());
198+
tracker->TrackFieldWithSize("shared_key", out_->shared_key.size());
199+
}
200+
CryptoJob<KEMEncapsulateTraits>::MemoryInfo(tracker);
203201
}
204202

205203
// KEMDecapsulateTraits implementation

β€Žsrc/crypto/crypto_kem.hβ€Ž

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -44,15 +44,30 @@ struct KEMEncapsulateTraits final {
4444
const v8::FunctionCallbackInfo<v8::Value>& args,
4545
unsignedint offset,
4646
KEMConfiguration* params);
47+
};
4748

48-
staticboolDeriveBits(Environment* env,
49-
const KEMConfiguration& params,
50-
ByteSource* out,
51-
CryptoJobMode mode);
49+
classKEMEncapsulateJobfinal : public CryptoJob<KEMEncapsulateTraits> {
50+
public:
51+
using AdditionalParams = KEMEncapsulateTraits::AdditionalParameters;
5252

53-
static v8::MaybeLocal<v8::Value> EncodeOutput(Environment* env,
54-
const KEMConfiguration& params,
55-
ByteSource* out);
53+
staticvoidNew(const v8::FunctionCallbackInfo<v8::Value>& args);
54+
staticvoidInitialize(Environment* env, v8::Local<v8::Object> target);
55+
staticvoidRegisterExternalReferences(ExternalReferenceRegistry* registry);
56+
57+
KEMEncapsulateJob(Environment* env,
58+
v8::Local<v8::Object> object,
59+
CryptoJobMode mode,
60+
AdditionalParams&& params);
61+
62+
voidDoThreadPoolWork() override;
63+
v8::Maybe<void> ToResult(v8::Local<v8::Value>* err,
64+
v8::Local<v8::Value>* result) override;
65+
66+
SET_SELF_SIZE(KEMEncapsulateJob)
67+
voidMemoryInfo(MemoryTracker* tracker) constoverride;
68+
69+
private:
70+
std::optional<ncrypto::KEM::EncapsulateResult> out_;
5671
};
5772

5873
structKEMDecapsulateTraitsfinal {
@@ -78,7 +93,6 @@ struct KEMDecapsulateTraits final {
7893
ByteSource* out);
7994
};
8095

81-
using KEMEncapsulateJob = DeriveBitsJob<KEMEncapsulateTraits>;
8296
using KEMDecapsulateJob = DeriveBitsJob<KEMDecapsulateTraits>;
8397

8498
voidInitializeKEM(Environment* env, v8::Local<v8::Object> target);

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 4afc15b

Browse files
panvaaduh95
authored andcommitted
src: avoid redundant KEM encapsulation copies
KEM encapsulation produces separate ciphertext and shared-secret allocations. The existing DeriveBitsJob path packs both values into an intermediate buffer, then copies them again into separate buffers. Instead, this uses a dedicated KEMEncapsulateJob to retain both outputs across the worker boundary and convert each directly through ByteSource. This removes the intermediate allocation and at least one complete round of copies. Signed-off-by: Filip Skokan <panva.ip@gmail.com> PR-URL: #64553 Backport-PR-URL: #65087 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com> Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
1 parent fea0666 commit 4afc15b

2 files changed

Lines changed: 116 additions & 104 deletions

File tree

β€Žsrc/crypto/crypto_kem.ccβ€Ž

Lines changed: 94 additions & 96 deletions
Original file line numberDiff line numberDiff line change
@@ -8,21 +8,20 @@
88
#include"crypto/crypto_util.h"
99
#include"env-inl.h"
1010
#include"memory_tracker-inl.h"
11-
#include"node_buffer.h"
1211
#include"threadpoolwork-inl.h"
1312
#include"v8.h"
1413

1514
namespacenode {
1615

1716
using ncrypto::EVPKeyPointer;
1817
using v8::Array;
19-
using v8::ArrayBufferView;
2018
using v8::FunctionCallbackInfo;
2119
using v8::Local;
2220
using v8::Maybe;
2321
using v8::MaybeLocal;
2422
using v8::Nothing;
2523
using v8::Object;
24+
using v8::Uint8Array;
2625
using v8::Value;
2726

2827
namespacecrypto {
@@ -49,51 +48,6 @@ void KEMConfiguration::MemoryInfo(MemoryTracker* tracker) const {
4948

5049
namespace {
5150

52-
boolDoKEMEncapsulate(Environment* env,
53-
const EVPKeyPointer& public_key,
54-
ByteSource* out,
55-
CryptoJobMode mode) {
56-
auto result = ncrypto::KEM::Encapsulate(public_key);
57-
if (!result) {
58-
if (mode == kCryptoJobSync) {
59-
THROW_ERR_CRYPTO_OPERATION_FAILED(env, "Failed to perform encapsulation");
60-
}
61-
returnfalse;
62-
}
63-
64-
// Pack the result: [ciphertext_len][shared_key_len][ciphertext][shared_key]
65-
size_t ciphertext_len = result->ciphertext.size();
66-
size_t shared_key_len = result->shared_key.size();
67-
size_t total_len =
68-
sizeof(uint32_t) + sizeof(uint32_t) + ciphertext_len + shared_key_len;
69-
70-
auto data = ncrypto::DataPointer::Alloc(total_len);
71-
if (!data) {
72-
if (mode == kCryptoJobSync) {
73-
THROW_ERR_CRYPTO_OPERATION_FAILED(env,
74-
"Failed to allocate output buffer");
75-
}
76-
returnfalse;
77-
}
78-
79-
unsignedchar* ptr = static_cast<unsignedchar*>(data.get());
80-
81-
// Write size headers
82-
*reinterpret_cast<uint32_t*>(ptr) = static_cast<uint32_t>(ciphertext_len);
83-
*reinterpret_cast<uint32_t*>(ptr + sizeof(uint32_t)) =
84-
static_cast<uint32_t>(shared_key_len);
85-
86-
// Write ciphertext and shared key data
87-
unsignedchar* ciphertext_ptr = ptr + 2 * sizeof(uint32_t);
88-
unsignedchar* shared_key_ptr = ciphertext_ptr + ciphertext_len;
89-
90-
std::memcpy(ciphertext_ptr, result->ciphertext.get(), ciphertext_len);
91-
std::memcpy(shared_key_ptr, result->shared_key.get(), shared_key_len);
92-
93-
*out = ByteSource::Allocated(data.release());
94-
returntrue;
95-
}
96-
9751
boolDoKEMDecapsulate(Environment* env,
9852
const EVPKeyPointer& private_key,
9953
const ByteSource& ciphertext,
@@ -135,71 +89,115 @@ Maybe<void> KEMEncapsulateTraits::AdditionalConfig(
13589
returnv8::JustVoid();
13690
}
13791

138-
boolKEMEncapsulateTraits::DeriveBits(Environment* env,
139-
const KEMConfiguration& params,
140-
ByteSource* out,
141-
CryptoJobMode mode) {
142-
Mutex::ScopedLock lock(params.key.mutex());
143-
constauto& public_key = params.key.GetAsymmetricKey();
92+
voidKEMEncapsulateJob::New(const FunctionCallbackInfo<Value>& args) {
93+
Environment* env = Environment::GetCurrent(args);
94+
CHECK(args.IsConstructCall());
95+
96+
CryptoJobMode mode = GetCryptoJobMode(args[0]);
97+
AdditionalParams params;
98+
if (KEMEncapsulateTraits::AdditionalConfig(mode, args, 1, &params)
99+
.IsNothing()) {
100+
return;
101+
}
144102

145-
returnDoKEMEncapsulate(env, public_key, out, mode);
103+
newKEMEncapsulateJob(env, args.This(), mode, std::move(params));
146104
}
147105

148-
MaybeLocal<Value> KEMEncapsulateTraits::EncodeOutput(
149-
Environment* env, const KEMConfiguration& params, ByteSource* out) {
150-
// The output contains:
151-
// [ciphertext_len][shared_key_len][ciphertext][shared_key]
152-
constunsignedchar* data = out->data<unsignedchar>();
153-
154-
uint32_t ciphertext_len = *reinterpret_cast<constuint32_t*>(data);
155-
uint32_t shared_key_len =
156-
*reinterpret_cast<constuint32_t*>(data + sizeof(uint32_t));
157-
158-
constunsignedchar* ciphertext_ptr = data + 2 * sizeof(uint32_t);
159-
constunsignedchar* shared_key_ptr = ciphertext_ptr + ciphertext_len;
160-
161-
MaybeLocal<Object> ciphertext_buf =
162-
node::Buffer::Copy(env->isolate(),
163-
reinterpret_cast<constchar*>(ciphertext_ptr),
164-
ciphertext_len);
165-
166-
MaybeLocal<Object> shared_key_buf =
167-
node::Buffer::Copy(env->isolate(),
168-
reinterpret_cast<constchar*>(shared_key_ptr),
169-
shared_key_len);
170-
171-
Local<Object> ciphertext_obj;
172-
Local<Object> shared_key_obj;
173-
if (!ciphertext_buf.ToLocal(&ciphertext_obj) ||
174-
!shared_key_buf.ToLocal(&shared_key_obj)) {
175-
return MaybeLocal<Value>();
106+
voidKEMEncapsulateJob::Initialize(Environment* env, Local<Object> target) {
107+
CryptoJob<KEMEncapsulateTraits>::Initialize(New, env, target);
108+
}
109+
110+
voidKEMEncapsulateJob::RegisterExternalReferences(
111+
ExternalReferenceRegistry* registry) {
112+
CryptoJob<KEMEncapsulateTraits>::RegisterExternalReferences(New, registry);
113+
}
114+
115+
KEMEncapsulateJob::KEMEncapsulateJob(Environment* env,
116+
Local<Object> object,
117+
CryptoJobMode mode,
118+
AdditionalParams&& params)
119+
: CryptoJob<KEMEncapsulateTraits>(env,
120+
object,
121+
KEMEncapsulateTraits::Provider,
122+
mode,
123+
std::move(params)) {}
124+
125+
voidKEMEncapsulateJob::DoThreadPoolWork() {
126+
ncrypto::ClearErrorOnReturn clear_error_on_return;
127+
AdditionalParams* params = CryptoJob<KEMEncapsulateTraits>::params();
128+
Mutex::ScopedLock lock(params->key.mutex());
129+
out_ = ncrypto::KEM::Encapsulate(params->key.GetAsymmetricKey());
130+
if (!out_) {
131+
if (mode() == kCryptoJobSync) {
132+
THROW_ERR_CRYPTO_OPERATION_FAILED(AsyncWrap::env(),
133+
"Failed to perform encapsulation");
134+
}
135+
CryptoErrorStore* errors = CryptoJob<KEMEncapsulateTraits>::errors();
136+
errors->Capture();
137+
if (errors->Empty()) {
138+
errors->Insert(NodeCryptoError::DERIVING_BITS_FAILED);
139+
}
176140
}
141+
}
177142

178-
if (params.job_mode == kCryptoJobWebCrypto) {
179-
Local<Object> result = Object::New(env->isolate());
180-
if (!result
143+
Maybe<void> KEMEncapsulateJob::ToResult(Local<Value>* err,
144+
Local<Value>* result) {
145+
Environment* env = AsyncWrap::env();
146+
CryptoErrorStore* errors = CryptoJob<KEMEncapsulateTraits>::errors();
147+
if (!out_) {
148+
if (errors->Empty()) errors->Capture();
149+
CHECK(!errors->Empty());
150+
*result = v8::Undefined(env->isolate());
151+
if (!errors->ToException(env).ToLocal(err)) return Nothing<void>();
152+
returnv8::JustVoid();
153+
}
154+
155+
CHECK(errors->Empty());
156+
*err = v8::Undefined(env->isolate());
157+
158+
ByteSource ciphertext = ByteSource::Allocated(out_->ciphertext.release());
159+
ByteSource shared_key = ByteSource::Allocated(out_->shared_key.release());
160+
161+
if (mode() == kCryptoJobWebCrypto) {
162+
Local<Object> output = Object::New(env->isolate());
163+
if (!output
181164
->DefineOwnProperty(env->context(),
182165
OneByteString(env->isolate(), "sharedKey"),
183-
shared_key_obj.As<ArrayBufferView>()->Buffer())
166+
shared_key.ToArrayBuffer(env))
184167
.FromMaybe(false) ||
185-
!result
168+
!output
186169
->DefineOwnProperty(env->context(),
187170
OneByteString(env->isolate(), "ciphertext"),
188-
ciphertext_obj.As<ArrayBufferView>()->Buffer())
171+
ciphertext.ToArrayBuffer(env))
189172
.FromMaybe(false)) {
190-
returnMaybeLocal<Value>();
173+
returnNothing<void>();
191174
}
192-
return result;
175+
*result = output;
176+
returnv8::JustVoid();
193177
}
194178

195-
// Return an array [sharedKey, ciphertext].
196-
Local<Array> result = Array::New(env->isolate(), 2);
197-
if (result->Set(env->context(), 0, shared_key_obj).IsNothing() ||
198-
result->Set(env->context(), 1, ciphertext_obj).IsNothing()) {
199-
returnMaybeLocal<Value>();
179+
Local<Uint8Array> shared_key_buf;
180+
Local<Uint8Array> ciphertext_buf;
181+
if (!shared_key.ToBuffer(env).ToLocal(&shared_key_buf) ||
182+
!ciphertext.ToBuffer(env).ToLocal(&ciphertext_buf)) {
183+
returnNothing<void>();
200184
}
201185

202-
return result;
186+
Local<Array> output = Array::New(env->isolate(), 2);
187+
if (output->Set(env->context(), 0, shared_key_buf).IsNothing() ||
188+
output->Set(env->context(), 1, ciphertext_buf).IsNothing()) {
189+
return Nothing<void>();
190+
}
191+
*result = output;
192+
returnv8::JustVoid();
193+
}
194+
195+
voidKEMEncapsulateJob::MemoryInfo(MemoryTracker* tracker) const {
196+
if (out_) {
197+
tracker->TrackFieldWithSize("ciphertext", out_->ciphertext.size());
198+
tracker->TrackFieldWithSize("shared_key", out_->shared_key.size());
199+
}
200+
CryptoJob<KEMEncapsulateTraits>::MemoryInfo(tracker);
203201
}
204202

205203
// KEMDecapsulateTraits implementation

β€Žsrc/crypto/crypto_kem.hβ€Ž

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -44,15 +44,30 @@ struct KEMEncapsulateTraits final {
4444
const v8::FunctionCallbackInfo<v8::Value>& args,
4545
unsignedint offset,
4646
KEMConfiguration* params);
47+
};
4748

48-
staticboolDeriveBits(Environment* env,
49-
const KEMConfiguration& params,
50-
ByteSource* out,
51-
CryptoJobMode mode);
49+
classKEMEncapsulateJobfinal : public CryptoJob<KEMEncapsulateTraits> {
50+
public:
51+
using AdditionalParams = KEMEncapsulateTraits::AdditionalParameters;
5252

53-
static v8::MaybeLocal<v8::Value> EncodeOutput(Environment* env,
54-
const KEMConfiguration& params,
55-
ByteSource* out);
53+
staticvoidNew(const v8::FunctionCallbackInfo<v8::Value>& args);
54+
staticvoidInitialize(Environment* env, v8::Local<v8::Object> target);
55+
staticvoidRegisterExternalReferences(ExternalReferenceRegistry* registry);
56+
57+
KEMEncapsulateJob(Environment* env,
58+
v8::Local<v8::Object> object,
59+
CryptoJobMode mode,
60+
AdditionalParams&& params);
61+
62+
voidDoThreadPoolWork() override;
63+
v8::Maybe<void> ToResult(v8::Local<v8::Value>* err,
64+
v8::Local<v8::Value>* result) override;
65+
66+
SET_SELF_SIZE(KEMEncapsulateJob)
67+
voidMemoryInfo(MemoryTracker* tracker) constoverride;
68+
69+
private:
70+
std::optional<ncrypto::KEM::EncapsulateResult> out_;
5671
};
5772

5873
structKEMDecapsulateTraitsfinal {
@@ -78,7 +93,6 @@ struct KEMDecapsulateTraits final {
7893
ByteSource* out);
7994
};
8095

81-
using KEMEncapsulateJob = DeriveBitsJob<KEMEncapsulateTraits>;
8296
using KEMDecapsulateJob = DeriveBitsJob<KEMDecapsulateTraits>;
8397

8498
voidInitializeKEM(Environment* env, v8::Local<v8::Object> target);

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 4afc15b

Browse files
panvaaduh95
authored andcommitted
src: avoid redundant KEM encapsulation copies
KEM encapsulation produces separate ciphertext and shared-secret allocations. The existing DeriveBitsJob path packs both values into an intermediate buffer, then copies them again into separate buffers. Instead, this uses a dedicated KEMEncapsulateJob to retain both outputs across the worker boundary and convert each directly through ByteSource. This removes the intermediate allocation and at least one complete round of copies. Signed-off-by: Filip Skokan <panva.ip@gmail.com> PR-URL: #64553 Backport-PR-URL: #65087 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com> Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
1 parent fea0666 commit 4afc15b

2 files changed

Lines changed: 116 additions & 104 deletions

File tree

β€Žsrc/crypto/crypto_kem.ccβ€Ž

Lines changed: 94 additions & 96 deletions
Original file line numberDiff line numberDiff line change
@@ -8,21 +8,20 @@
88
#include"crypto/crypto_util.h"
99
#include"env-inl.h"
1010
#include"memory_tracker-inl.h"
11-
#include"node_buffer.h"
1211
#include"threadpoolwork-inl.h"
1312
#include"v8.h"
1413

1514
namespacenode {
1615

1716
using ncrypto::EVPKeyPointer;
1817
using v8::Array;
19-
using v8::ArrayBufferView;
2018
using v8::FunctionCallbackInfo;
2119
using v8::Local;
2220
using v8::Maybe;
2321
using v8::MaybeLocal;
2422
using v8::Nothing;
2523
using v8::Object;
24+
using v8::Uint8Array;
2625
using v8::Value;
2726

2827
namespacecrypto {
@@ -49,51 +48,6 @@ void KEMConfiguration::MemoryInfo(MemoryTracker* tracker) const {
4948

5049
namespace {
5150

52-
boolDoKEMEncapsulate(Environment* env,
53-
const EVPKeyPointer& public_key,
54-
ByteSource* out,
55-
CryptoJobMode mode) {
56-
auto result = ncrypto::KEM::Encapsulate(public_key);
57-
if (!result) {
58-
if (mode == kCryptoJobSync) {
59-
THROW_ERR_CRYPTO_OPERATION_FAILED(env, "Failed to perform encapsulation");
60-
}
61-
returnfalse;
62-
}
63-
64-
// Pack the result: [ciphertext_len][shared_key_len][ciphertext][shared_key]
65-
size_t ciphertext_len = result->ciphertext.size();
66-
size_t shared_key_len = result->shared_key.size();
67-
size_t total_len =
68-
sizeof(uint32_t) + sizeof(uint32_t) + ciphertext_len + shared_key_len;
69-
70-
auto data = ncrypto::DataPointer::Alloc(total_len);
71-
if (!data) {
72-
if (mode == kCryptoJobSync) {
73-
THROW_ERR_CRYPTO_OPERATION_FAILED(env,
74-
"Failed to allocate output buffer");
75-
}
76-
returnfalse;
77-
}
78-
79-
unsignedchar* ptr = static_cast<unsignedchar*>(data.get());
80-
81-
// Write size headers
82-
*reinterpret_cast<uint32_t*>(ptr) = static_cast<uint32_t>(ciphertext_len);
83-
*reinterpret_cast<uint32_t*>(ptr + sizeof(uint32_t)) =
84-
static_cast<uint32_t>(shared_key_len);
85-
86-
// Write ciphertext and shared key data
87-
unsignedchar* ciphertext_ptr = ptr + 2 * sizeof(uint32_t);
88-
unsignedchar* shared_key_ptr = ciphertext_ptr + ciphertext_len;
89-
90-
std::memcpy(ciphertext_ptr, result->ciphertext.get(), ciphertext_len);
91-
std::memcpy(shared_key_ptr, result->shared_key.get(), shared_key_len);
92-
93-
*out = ByteSource::Allocated(data.release());
94-
returntrue;
95-
}
96-
9751
boolDoKEMDecapsulate(Environment* env,
9852
const EVPKeyPointer& private_key,
9953
const ByteSource& ciphertext,
@@ -135,71 +89,115 @@ Maybe<void> KEMEncapsulateTraits::AdditionalConfig(
13589
returnv8::JustVoid();
13690
}
13791

138-
boolKEMEncapsulateTraits::DeriveBits(Environment* env,
139-
const KEMConfiguration& params,
140-
ByteSource* out,
141-
CryptoJobMode mode) {
142-
Mutex::ScopedLock lock(params.key.mutex());
143-
constauto& public_key = params.key.GetAsymmetricKey();
92+
voidKEMEncapsulateJob::New(const FunctionCallbackInfo<Value>& args) {
93+
Environment* env = Environment::GetCurrent(args);
94+
CHECK(args.IsConstructCall());
95+
96+
CryptoJobMode mode = GetCryptoJobMode(args[0]);
97+
AdditionalParams params;
98+
if (KEMEncapsulateTraits::AdditionalConfig(mode, args, 1, &params)
99+
.IsNothing()) {
100+
return;
101+
}
144102

145-
returnDoKEMEncapsulate(env, public_key, out, mode);
103+
newKEMEncapsulateJob(env, args.This(), mode, std::move(params));
146104
}
147105

148-
MaybeLocal<Value> KEMEncapsulateTraits::EncodeOutput(
149-
Environment* env, const KEMConfiguration& params, ByteSource* out) {
150-
// The output contains:
151-
// [ciphertext_len][shared_key_len][ciphertext][shared_key]
152-
constunsignedchar* data = out->data<unsignedchar>();
153-
154-
uint32_t ciphertext_len = *reinterpret_cast<constuint32_t*>(data);
155-
uint32_t shared_key_len =
156-
*reinterpret_cast<constuint32_t*>(data + sizeof(uint32_t));
157-
158-
constunsignedchar* ciphertext_ptr = data + 2 * sizeof(uint32_t);
159-
constunsignedchar* shared_key_ptr = ciphertext_ptr + ciphertext_len;
160-
161-
MaybeLocal<Object> ciphertext_buf =
162-
node::Buffer::Copy(env->isolate(),
163-
reinterpret_cast<constchar*>(ciphertext_ptr),
164-
ciphertext_len);
165-
166-
MaybeLocal<Object> shared_key_buf =
167-
node::Buffer::Copy(env->isolate(),
168-
reinterpret_cast<constchar*>(shared_key_ptr),
169-
shared_key_len);
170-
171-
Local<Object> ciphertext_obj;
172-
Local<Object> shared_key_obj;
173-
if (!ciphertext_buf.ToLocal(&ciphertext_obj) ||
174-
!shared_key_buf.ToLocal(&shared_key_obj)) {
175-
return MaybeLocal<Value>();
106+
voidKEMEncapsulateJob::Initialize(Environment* env, Local<Object> target) {
107+
CryptoJob<KEMEncapsulateTraits>::Initialize(New, env, target);
108+
}
109+
110+
voidKEMEncapsulateJob::RegisterExternalReferences(
111+
ExternalReferenceRegistry* registry) {
112+
CryptoJob<KEMEncapsulateTraits>::RegisterExternalReferences(New, registry);
113+
}
114+
115+
KEMEncapsulateJob::KEMEncapsulateJob(Environment* env,
116+
Local<Object> object,
117+
CryptoJobMode mode,
118+
AdditionalParams&& params)
119+
: CryptoJob<KEMEncapsulateTraits>(env,
120+
object,
121+
KEMEncapsulateTraits::Provider,
122+
mode,
123+
std::move(params)) {}
124+
125+
voidKEMEncapsulateJob::DoThreadPoolWork() {
126+
ncrypto::ClearErrorOnReturn clear_error_on_return;
127+
AdditionalParams* params = CryptoJob<KEMEncapsulateTraits>::params();
128+
Mutex::ScopedLock lock(params->key.mutex());
129+
out_ = ncrypto::KEM::Encapsulate(params->key.GetAsymmetricKey());
130+
if (!out_) {
131+
if (mode() == kCryptoJobSync) {
132+
THROW_ERR_CRYPTO_OPERATION_FAILED(AsyncWrap::env(),
133+
"Failed to perform encapsulation");
134+
}
135+
CryptoErrorStore* errors = CryptoJob<KEMEncapsulateTraits>::errors();
136+
errors->Capture();
137+
if (errors->Empty()) {
138+
errors->Insert(NodeCryptoError::DERIVING_BITS_FAILED);
139+
}
176140
}
141+
}
177142

178-
if (params.job_mode == kCryptoJobWebCrypto) {
179-
Local<Object> result = Object::New(env->isolate());
180-
if (!result
143+
Maybe<void> KEMEncapsulateJob::ToResult(Local<Value>* err,
144+
Local<Value>* result) {
145+
Environment* env = AsyncWrap::env();
146+
CryptoErrorStore* errors = CryptoJob<KEMEncapsulateTraits>::errors();
147+
if (!out_) {
148+
if (errors->Empty()) errors->Capture();
149+
CHECK(!errors->Empty());
150+
*result = v8::Undefined(env->isolate());
151+
if (!errors->ToException(env).ToLocal(err)) return Nothing<void>();
152+
returnv8::JustVoid();
153+
}
154+
155+
CHECK(errors->Empty());
156+
*err = v8::Undefined(env->isolate());
157+
158+
ByteSource ciphertext = ByteSource::Allocated(out_->ciphertext.release());
159+
ByteSource shared_key = ByteSource::Allocated(out_->shared_key.release());
160+
161+
if (mode() == kCryptoJobWebCrypto) {
162+
Local<Object> output = Object::New(env->isolate());
163+
if (!output
181164
->DefineOwnProperty(env->context(),
182165
OneByteString(env->isolate(), "sharedKey"),
183-
shared_key_obj.As<ArrayBufferView>()->Buffer())
166+
shared_key.ToArrayBuffer(env))
184167
.FromMaybe(false) ||
185-
!result
168+
!output
186169
->DefineOwnProperty(env->context(),
187170
OneByteString(env->isolate(), "ciphertext"),
188-
ciphertext_obj.As<ArrayBufferView>()->Buffer())
171+
ciphertext.ToArrayBuffer(env))
189172
.FromMaybe(false)) {
190-
returnMaybeLocal<Value>();
173+
returnNothing<void>();
191174
}
192-
return result;
175+
*result = output;
176+
returnv8::JustVoid();
193177
}
194178

195-
// Return an array [sharedKey, ciphertext].
196-
Local<Array> result = Array::New(env->isolate(), 2);
197-
if (result->Set(env->context(), 0, shared_key_obj).IsNothing() ||
198-
result->Set(env->context(), 1, ciphertext_obj).IsNothing()) {
199-
returnMaybeLocal<Value>();
179+
Local<Uint8Array> shared_key_buf;
180+
Local<Uint8Array> ciphertext_buf;
181+
if (!shared_key.ToBuffer(env).ToLocal(&shared_key_buf) ||
182+
!ciphertext.ToBuffer(env).ToLocal(&ciphertext_buf)) {
183+
returnNothing<void>();
200184
}
201185

202-
return result;
186+
Local<Array> output = Array::New(env->isolate(), 2);
187+
if (output->Set(env->context(), 0, shared_key_buf).IsNothing() ||
188+
output->Set(env->context(), 1, ciphertext_buf).IsNothing()) {
189+
return Nothing<void>();
190+
}
191+
*result = output;
192+
returnv8::JustVoid();
193+
}
194+
195+
voidKEMEncapsulateJob::MemoryInfo(MemoryTracker* tracker) const {
196+
if (out_) {
197+
tracker->TrackFieldWithSize("ciphertext", out_->ciphertext.size());
198+
tracker->TrackFieldWithSize("shared_key", out_->shared_key.size());
199+
}
200+
CryptoJob<KEMEncapsulateTraits>::MemoryInfo(tracker);
203201
}
204202

205203
// KEMDecapsulateTraits implementation

β€Žsrc/crypto/crypto_kem.hβ€Ž

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -44,15 +44,30 @@ struct KEMEncapsulateTraits final {
4444
const v8::FunctionCallbackInfo<v8::Value>& args,
4545
unsignedint offset,
4646
KEMConfiguration* params);
47+
};
4748

48-
staticboolDeriveBits(Environment* env,
49-
const KEMConfiguration& params,
50-
ByteSource* out,
51-
CryptoJobMode mode);
49+
classKEMEncapsulateJobfinal : public CryptoJob<KEMEncapsulateTraits> {
50+
public:
51+
using AdditionalParams = KEMEncapsulateTraits::AdditionalParameters;
5252

53-
static v8::MaybeLocal<v8::Value> EncodeOutput(Environment* env,
54-
const KEMConfiguration& params,
55-
ByteSource* out);
53+
staticvoidNew(const v8::FunctionCallbackInfo<v8::Value>& args);
54+
staticvoidInitialize(Environment* env, v8::Local<v8::Object> target);
55+
staticvoidRegisterExternalReferences(ExternalReferenceRegistry* registry);
56+
57+
KEMEncapsulateJob(Environment* env,
58+
v8::Local<v8::Object> object,
59+
CryptoJobMode mode,
60+
AdditionalParams&& params);
61+
62+
voidDoThreadPoolWork() override;
63+
v8::Maybe<void> ToResult(v8::Local<v8::Value>* err,
64+
v8::Local<v8::Value>* result) override;
65+
66+
SET_SELF_SIZE(KEMEncapsulateJob)
67+
voidMemoryInfo(MemoryTracker* tracker) constoverride;
68+
69+
private:
70+
std::optional<ncrypto::KEM::EncapsulateResult> out_;
5671
};
5772

5873
structKEMDecapsulateTraitsfinal {
@@ -78,7 +93,6 @@ struct KEMDecapsulateTraits final {
7893
ByteSource* out);
7994
};
8095

81-
using KEMEncapsulateJob = DeriveBitsJob<KEMEncapsulateTraits>;
8296
using KEMDecapsulateJob = DeriveBitsJob<KEMDecapsulateTraits>;
8397

8498
voidInitializeKEM(Environment* env, v8::Local<v8::Object> target);

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Commit 4afc15b

Browse files
panvaaduh95
authored andcommitted
src: avoid redundant KEM encapsulation copies
KEM encapsulation produces separate ciphertext and shared-secret allocations. The existing DeriveBitsJob path packs both values into an intermediate buffer, then copies them again into separate buffers. Instead, this uses a dedicated KEMEncapsulateJob to retain both outputs across the worker boundary and convert each directly through ByteSource. This removes the intermediate allocation and at least one complete round of copies. Signed-off-by: Filip Skokan <panva.ip@gmail.com> PR-URL: #64553 Backport-PR-URL: #65087 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com> Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
1 parent fea0666 commit 4afc15b

2 files changed

Lines changed: 116 additions & 104 deletions

File tree

β€Žsrc/crypto/crypto_kem.ccβ€Ž

Lines changed: 94 additions & 96 deletions
Original file line numberDiff line numberDiff line change
@@ -8,21 +8,20 @@
88
#include"crypto/crypto_util.h"
99
#include"env-inl.h"
1010
#include"memory_tracker-inl.h"
11-
#include"node_buffer.h"
1211
#include"threadpoolwork-inl.h"
1312
#include"v8.h"
1413

1514
namespacenode {
1615

1716
using ncrypto::EVPKeyPointer;
1817
using v8::Array;
19-
using v8::ArrayBufferView;
2018
using v8::FunctionCallbackInfo;
2119
using v8::Local;
2220
using v8::Maybe;
2321
using v8::MaybeLocal;
2422
using v8::Nothing;
2523
using v8::Object;
24+
using v8::Uint8Array;
2625
using v8::Value;
2726

2827
namespacecrypto {
@@ -49,51 +48,6 @@ void KEMConfiguration::MemoryInfo(MemoryTracker* tracker) const {
4948

5049
namespace {
5150

52-
boolDoKEMEncapsulate(Environment* env,
53-
const EVPKeyPointer& public_key,
54-
ByteSource* out,
55-
CryptoJobMode mode) {
56-
auto result = ncrypto::KEM::Encapsulate(public_key);
57-
if (!result) {
58-
if (mode == kCryptoJobSync) {
59-
THROW_ERR_CRYPTO_OPERATION_FAILED(env, "Failed to perform encapsulation");
60-
}
61-
returnfalse;
62-
}
63-
64-
// Pack the result: [ciphertext_len][shared_key_len][ciphertext][shared_key]
65-
size_t ciphertext_len = result->ciphertext.size();
66-
size_t shared_key_len = result->shared_key.size();
67-
size_t total_len =
68-
sizeof(uint32_t) + sizeof(uint32_t) + ciphertext_len + shared_key_len;
69-
70-
auto data = ncrypto::DataPointer::Alloc(total_len);
71-
if (!data) {
72-
if (mode == kCryptoJobSync) {
73-
THROW_ERR_CRYPTO_OPERATION_FAILED(env,
74-
"Failed to allocate output buffer");
75-
}
76-
returnfalse;
77-
}
78-
79-
unsignedchar* ptr = static_cast<unsignedchar*>(data.get());
80-
81-
// Write size headers
82-
*reinterpret_cast<uint32_t*>(ptr) = static_cast<uint32_t>(ciphertext_len);
83-
*reinterpret_cast<uint32_t*>(ptr + sizeof(uint32_t)) =
84-
static_cast<uint32_t>(shared_key_len);
85-
86-
// Write ciphertext and shared key data
87-
unsignedchar* ciphertext_ptr = ptr + 2 * sizeof(uint32_t);
88-
unsignedchar* shared_key_ptr = ciphertext_ptr + ciphertext_len;
89-
90-
std::memcpy(ciphertext_ptr, result->ciphertext.get(), ciphertext_len);
91-
std::memcpy(shared_key_ptr, result->shared_key.get(), shared_key_len);
92-
93-
*out = ByteSource::Allocated(data.release());
94-
returntrue;
95-
}
96-
9751
boolDoKEMDecapsulate(Environment* env,
9852
const EVPKeyPointer& private_key,
9953
const ByteSource& ciphertext,
@@ -135,71 +89,115 @@ Maybe<void> KEMEncapsulateTraits::AdditionalConfig(
13589
returnv8::JustVoid();
13690
}
13791

138-
boolKEMEncapsulateTraits::DeriveBits(Environment* env,
139-
const KEMConfiguration& params,
140-
ByteSource* out,
141-
CryptoJobMode mode) {
142-
Mutex::ScopedLock lock(params.key.mutex());
143-
constauto& public_key = params.key.GetAsymmetricKey();
92+
voidKEMEncapsulateJob::New(const FunctionCallbackInfo<Value>& args) {
93+
Environment* env = Environment::GetCurrent(args);
94+
CHECK(args.IsConstructCall());
95+
96+
CryptoJobMode mode = GetCryptoJobMode(args[0]);
97+
AdditionalParams params;
98+
if (KEMEncapsulateTraits::AdditionalConfig(mode, args, 1, &params)
99+
.IsNothing()) {
100+
return;
101+
}
144102

145-
returnDoKEMEncapsulate(env, public_key, out, mode);
103+
newKEMEncapsulateJob(env, args.This(), mode, std::move(params));
146104
}
147105

148-
MaybeLocal<Value> KEMEncapsulateTraits::EncodeOutput(
149-
Environment* env, const KEMConfiguration& params, ByteSource* out) {
150-
// The output contains:
151-
// [ciphertext_len][shared_key_len][ciphertext][shared_key]
152-
constunsignedchar* data = out->data<unsignedchar>();
153-
154-
uint32_t ciphertext_len = *reinterpret_cast<constuint32_t*>(data);
155-
uint32_t shared_key_len =
156-
*reinterpret_cast<constuint32_t*>(data + sizeof(uint32_t));
157-
158-
constunsignedchar* ciphertext_ptr = data + 2 * sizeof(uint32_t);
159-
constunsignedchar* shared_key_ptr = ciphertext_ptr + ciphertext_len;
160-
161-
MaybeLocal<Object> ciphertext_buf =
162-
node::Buffer::Copy(env->isolate(),
163-
reinterpret_cast<constchar*>(ciphertext_ptr),
164-
ciphertext_len);
165-
166-
MaybeLocal<Object> shared_key_buf =
167-
node::Buffer::Copy(env->isolate(),
168-
reinterpret_cast<constchar*>(shared_key_ptr),
169-
shared_key_len);
170-
171-
Local<Object> ciphertext_obj;
172-
Local<Object> shared_key_obj;
173-
if (!ciphertext_buf.ToLocal(&ciphertext_obj) ||
174-
!shared_key_buf.ToLocal(&shared_key_obj)) {
175-
return MaybeLocal<Value>();
106+
voidKEMEncapsulateJob::Initialize(Environment* env, Local<Object> target) {
107+
CryptoJob<KEMEncapsulateTraits>::Initialize(New, env, target);
108+
}
109+
110+
voidKEMEncapsulateJob::RegisterExternalReferences(
111+
ExternalReferenceRegistry* registry) {
112+
CryptoJob<KEMEncapsulateTraits>::RegisterExternalReferences(New, registry);
113+
}
114+
115+
KEMEncapsulateJob::KEMEncapsulateJob(Environment* env,
116+
Local<Object> object,
117+
CryptoJobMode mode,
118+
AdditionalParams&& params)
119+
: CryptoJob<KEMEncapsulateTraits>(env,
120+
object,
121+
KEMEncapsulateTraits::Provider,
122+
mode,
123+
std::move(params)) {}
124+
125+
voidKEMEncapsulateJob::DoThreadPoolWork() {
126+
ncrypto::ClearErrorOnReturn clear_error_on_return;
127+
AdditionalParams* params = CryptoJob<KEMEncapsulateTraits>::params();
128+
Mutex::ScopedLock lock(params->key.mutex());
129+
out_ = ncrypto::KEM::Encapsulate(params->key.GetAsymmetricKey());
130+
if (!out_) {
131+
if (mode() == kCryptoJobSync) {
132+
THROW_ERR_CRYPTO_OPERATION_FAILED(AsyncWrap::env(),
133+
"Failed to perform encapsulation");
134+
}
135+
CryptoErrorStore* errors = CryptoJob<KEMEncapsulateTraits>::errors();
136+
errors->Capture();
137+
if (errors->Empty()) {
138+
errors->Insert(NodeCryptoError::DERIVING_BITS_FAILED);
139+
}
176140
}
141+
}
177142

178-
if (params.job_mode == kCryptoJobWebCrypto) {
179-
Local<Object> result = Object::New(env->isolate());
180-
if (!result
143+
Maybe<void> KEMEncapsulateJob::ToResult(Local<Value>* err,
144+
Local<Value>* result) {
145+
Environment* env = AsyncWrap::env();
146+
CryptoErrorStore* errors = CryptoJob<KEMEncapsulateTraits>::errors();
147+
if (!out_) {
148+
if (errors->Empty()) errors->Capture();
149+
CHECK(!errors->Empty());
150+
*result = v8::Undefined(env->isolate());
151+
if (!errors->ToException(env).ToLocal(err)) return Nothing<void>();
152+
returnv8::JustVoid();
153+
}
154+
155+
CHECK(errors->Empty());
156+
*err = v8::Undefined(env->isolate());
157+
158+
ByteSource ciphertext = ByteSource::Allocated(out_->ciphertext.release());
159+
ByteSource shared_key = ByteSource::Allocated(out_->shared_key.release());
160+
161+
if (mode() == kCryptoJobWebCrypto) {
162+
Local<Object> output = Object::New(env->isolate());
163+
if (!output
181164
->DefineOwnProperty(env->context(),
182165
OneByteString(env->isolate(), "sharedKey"),
183-
shared_key_obj.As<ArrayBufferView>()->Buffer())
166+
shared_key.ToArrayBuffer(env))
184167
.FromMaybe(false) ||
185-
!result
168+
!output
186169
->DefineOwnProperty(env->context(),
187170
OneByteString(env->isolate(), "ciphertext"),
188-
ciphertext_obj.As<ArrayBufferView>()->Buffer())
171+
ciphertext.ToArrayBuffer(env))
189172
.FromMaybe(false)) {
190-
returnMaybeLocal<Value>();
173+
returnNothing<void>();
191174
}
192-
return result;
175+
*result = output;
176+
returnv8::JustVoid();
193177
}
194178

195-
// Return an array [sharedKey, ciphertext].
196-
Local<Array> result = Array::New(env->isolate(), 2);
197-
if (result->Set(env->context(), 0, shared_key_obj).IsNothing() ||
198-
result->Set(env->context(), 1, ciphertext_obj).IsNothing()) {
199-
returnMaybeLocal<Value>();
179+
Local<Uint8Array> shared_key_buf;
180+
Local<Uint8Array> ciphertext_buf;
181+
if (!shared_key.ToBuffer(env).ToLocal(&shared_key_buf) ||
182+
!ciphertext.ToBuffer(env).ToLocal(&ciphertext_buf)) {
183+
returnNothing<void>();
200184
}
201185

202-
return result;
186+
Local<Array> output = Array::New(env->isolate(), 2);
187+
if (output->Set(env->context(), 0, shared_key_buf).IsNothing() ||
188+
output->Set(env->context(), 1, ciphertext_buf).IsNothing()) {
189+
return Nothing<void>();
190+
}
191+
*result = output;
192+
returnv8::JustVoid();
193+
}
194+
195+
voidKEMEncapsulateJob::MemoryInfo(MemoryTracker* tracker) const {
196+
if (out_) {
197+
tracker->TrackFieldWithSize("ciphertext", out_->ciphertext.size());
198+
tracker->TrackFieldWithSize("shared_key", out_->shared_key.size());
199+
}
200+
CryptoJob<KEMEncapsulateTraits>::MemoryInfo(tracker);
203201
}
204202

205203
// KEMDecapsulateTraits implementation

β€Žsrc/crypto/crypto_kem.hβ€Ž

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -44,15 +44,30 @@ struct KEMEncapsulateTraits final {
4444
const v8::FunctionCallbackInfo<v8::Value>& args,
4545
unsignedint offset,
4646
KEMConfiguration* params);
47+
};
4748

48-
staticboolDeriveBits(Environment* env,
49-
const KEMConfiguration& params,
50-
ByteSource* out,
51-
CryptoJobMode mode);
49+
classKEMEncapsulateJobfinal : public CryptoJob<KEMEncapsulateTraits> {
50+
public:
51+
using AdditionalParams = KEMEncapsulateTraits::AdditionalParameters;
5252

53-
static v8::MaybeLocal<v8::Value> EncodeOutput(Environment* env,
54-
const KEMConfiguration& params,
55-
ByteSource* out);
53+
staticvoidNew(const v8::FunctionCallbackInfo<v8::Value>& args);
54+
staticvoidInitialize(Environment* env, v8::Local<v8::Object> target);
55+
staticvoidRegisterExternalReferences(ExternalReferenceRegistry* registry);
56+
57+
KEMEncapsulateJob(Environment* env,
58+
v8::Local<v8::Object> object,
59+
CryptoJobMode mode,
60+
AdditionalParams&& params);
61+
62+
voidDoThreadPoolWork() override;
63+
v8::Maybe<void> ToResult(v8::Local<v8::Value>* err,
64+
v8::Local<v8::Value>* result) override;
65+
66+
SET_SELF_SIZE(KEMEncapsulateJob)
67+
voidMemoryInfo(MemoryTracker* tracker) constoverride;
68+
69+
private:
70+
std::optional<ncrypto::KEM::EncapsulateResult> out_;
5671
};
5772

5873
structKEMDecapsulateTraitsfinal {
@@ -78,7 +93,6 @@ struct KEMDecapsulateTraits final {
7893
ByteSource* out);
7994
};
8095

81-
using KEMEncapsulateJob = DeriveBitsJob<KEMEncapsulateTraits>;
8296
using KEMDecapsulateJob = DeriveBitsJob<KEMDecapsulateTraits>;
8397

8498
voidInitializeKEM(Environment* env, v8::Local<v8::Object> target);

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 4afc15b

Browse files
panvaaduh95
authored andcommitted
src: avoid redundant KEM encapsulation copies
KEM encapsulation produces separate ciphertext and shared-secret allocations. The existing DeriveBitsJob path packs both values into an intermediate buffer, then copies them again into separate buffers. Instead, this uses a dedicated KEMEncapsulateJob to retain both outputs across the worker boundary and convert each directly through ByteSource. This removes the intermediate allocation and at least one complete round of copies. Signed-off-by: Filip Skokan <panva.ip@gmail.com> PR-URL: #64553 Backport-PR-URL: #65087 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com> Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
1 parent fea0666 commit 4afc15b

2 files changed

Lines changed: 116 additions & 104 deletions

File tree

β€Žsrc/crypto/crypto_kem.ccβ€Ž

Lines changed: 94 additions & 96 deletions
Original file line numberDiff line numberDiff line change
@@ -8,21 +8,20 @@
88
#include"crypto/crypto_util.h"
99
#include"env-inl.h"
1010
#include"memory_tracker-inl.h"
11-
#include"node_buffer.h"
1211
#include"threadpoolwork-inl.h"
1312
#include"v8.h"
1413

1514
namespacenode {
1615

1716
using ncrypto::EVPKeyPointer;
1817
using v8::Array;
19-
using v8::ArrayBufferView;
2018
using v8::FunctionCallbackInfo;
2119
using v8::Local;
2220
using v8::Maybe;
2321
using v8::MaybeLocal;
2422
using v8::Nothing;
2523
using v8::Object;
24+
using v8::Uint8Array;
2625
using v8::Value;
2726

2827
namespacecrypto {
@@ -49,51 +48,6 @@ void KEMConfiguration::MemoryInfo(MemoryTracker* tracker) const {
4948

5049
namespace {
5150

52-
boolDoKEMEncapsulate(Environment* env,
53-
const EVPKeyPointer& public_key,
54-
ByteSource* out,
55-
CryptoJobMode mode) {
56-
auto result = ncrypto::KEM::Encapsulate(public_key);
57-
if (!result) {
58-
if (mode == kCryptoJobSync) {
59-
THROW_ERR_CRYPTO_OPERATION_FAILED(env, "Failed to perform encapsulation");
60-
}
61-
returnfalse;
62-
}
63-
64-
// Pack the result: [ciphertext_len][shared_key_len][ciphertext][shared_key]
65-
size_t ciphertext_len = result->ciphertext.size();
66-
size_t shared_key_len = result->shared_key.size();
67-
size_t total_len =
68-
sizeof(uint32_t) + sizeof(uint32_t) + ciphertext_len + shared_key_len;
69-
70-
auto data = ncrypto::DataPointer::Alloc(total_len);
71-
if (!data) {
72-
if (mode == kCryptoJobSync) {
73-
THROW_ERR_CRYPTO_OPERATION_FAILED(env,
74-
"Failed to allocate output buffer");
75-
}
76-
returnfalse;
77-
}
78-
79-
unsignedchar* ptr = static_cast<unsignedchar*>(data.get());
80-
81-
// Write size headers
82-
*reinterpret_cast<uint32_t*>(ptr) = static_cast<uint32_t>(ciphertext_len);
83-
*reinterpret_cast<uint32_t*>(ptr + sizeof(uint32_t)) =
84-
static_cast<uint32_t>(shared_key_len);
85-
86-
// Write ciphertext and shared key data
87-
unsignedchar* ciphertext_ptr = ptr + 2 * sizeof(uint32_t);
88-
unsignedchar* shared_key_ptr = ciphertext_ptr + ciphertext_len;
89-
90-
std::memcpy(ciphertext_ptr, result->ciphertext.get(), ciphertext_len);
91-
std::memcpy(shared_key_ptr, result->shared_key.get(), shared_key_len);
92-
93-
*out = ByteSource::Allocated(data.release());
94-
returntrue;
95-
}
96-
9751
boolDoKEMDecapsulate(Environment* env,
9852
const EVPKeyPointer& private_key,
9953
const ByteSource& ciphertext,
@@ -135,71 +89,115 @@ Maybe<void> KEMEncapsulateTraits::AdditionalConfig(
13589
returnv8::JustVoid();
13690
}
13791

138-
boolKEMEncapsulateTraits::DeriveBits(Environment* env,
139-
const KEMConfiguration& params,
140-
ByteSource* out,
141-
CryptoJobMode mode) {
142-
Mutex::ScopedLock lock(params.key.mutex());
143-
constauto& public_key = params.key.GetAsymmetricKey();
92+
voidKEMEncapsulateJob::New(const FunctionCallbackInfo<Value>& args) {
93+
Environment* env = Environment::GetCurrent(args);
94+
CHECK(args.IsConstructCall());
95+
96+
CryptoJobMode mode = GetCryptoJobMode(args[0]);
97+
AdditionalParams params;
98+
if (KEMEncapsulateTraits::AdditionalConfig(mode, args, 1, &params)
99+
.IsNothing()) {
100+
return;
101+
}
144102

145-
returnDoKEMEncapsulate(env, public_key, out, mode);
103+
newKEMEncapsulateJob(env, args.This(), mode, std::move(params));
146104
}
147105

148-
MaybeLocal<Value> KEMEncapsulateTraits::EncodeOutput(
149-
Environment* env, const KEMConfiguration& params, ByteSource* out) {
150-
// The output contains:
151-
// [ciphertext_len][shared_key_len][ciphertext][shared_key]
152-
constunsignedchar* data = out->data<unsignedchar>();
153-
154-
uint32_t ciphertext_len = *reinterpret_cast<constuint32_t*>(data);
155-
uint32_t shared_key_len =
156-
*reinterpret_cast<constuint32_t*>(data + sizeof(uint32_t));
157-
158-
constunsignedchar* ciphertext_ptr = data + 2 * sizeof(uint32_t);
159-
constunsignedchar* shared_key_ptr = ciphertext_ptr + ciphertext_len;
160-
161-
MaybeLocal<Object> ciphertext_buf =
162-
node::Buffer::Copy(env->isolate(),
163-
reinterpret_cast<constchar*>(ciphertext_ptr),
164-
ciphertext_len);
165-
166-
MaybeLocal<Object> shared_key_buf =
167-
node::Buffer::Copy(env->isolate(),
168-
reinterpret_cast<constchar*>(shared_key_ptr),
169-
shared_key_len);
170-
171-
Local<Object> ciphertext_obj;
172-
Local<Object> shared_key_obj;
173-
if (!ciphertext_buf.ToLocal(&ciphertext_obj) ||
174-
!shared_key_buf.ToLocal(&shared_key_obj)) {
175-
return MaybeLocal<Value>();
106+
voidKEMEncapsulateJob::Initialize(Environment* env, Local<Object> target) {
107+
CryptoJob<KEMEncapsulateTraits>::Initialize(New, env, target);
108+
}
109+
110+
voidKEMEncapsulateJob::RegisterExternalReferences(
111+
ExternalReferenceRegistry* registry) {
112+
CryptoJob<KEMEncapsulateTraits>::RegisterExternalReferences(New, registry);
113+
}
114+
115+
KEMEncapsulateJob::KEMEncapsulateJob(Environment* env,
116+
Local<Object> object,
117+
CryptoJobMode mode,
118+
AdditionalParams&& params)
119+
: CryptoJob<KEMEncapsulateTraits>(env,
120+
object,
121+
KEMEncapsulateTraits::Provider,
122+
mode,
123+
std::move(params)) {}
124+
125+
voidKEMEncapsulateJob::DoThreadPoolWork() {
126+
ncrypto::ClearErrorOnReturn clear_error_on_return;
127+
AdditionalParams* params = CryptoJob<KEMEncapsulateTraits>::params();
128+
Mutex::ScopedLock lock(params->key.mutex());
129+
out_ = ncrypto::KEM::Encapsulate(params->key.GetAsymmetricKey());
130+
if (!out_) {
131+
if (mode() == kCryptoJobSync) {
132+
THROW_ERR_CRYPTO_OPERATION_FAILED(AsyncWrap::env(),
133+
"Failed to perform encapsulation");
134+
}
135+
CryptoErrorStore* errors = CryptoJob<KEMEncapsulateTraits>::errors();
136+
errors->Capture();
137+
if (errors->Empty()) {
138+
errors->Insert(NodeCryptoError::DERIVING_BITS_FAILED);
139+
}
176140
}
141+
}
177142

178-
if (params.job_mode == kCryptoJobWebCrypto) {
179-
Local<Object> result = Object::New(env->isolate());
180-
if (!result
143+
Maybe<void> KEMEncapsulateJob::ToResult(Local<Value>* err,
144+
Local<Value>* result) {
145+
Environment* env = AsyncWrap::env();
146+
CryptoErrorStore* errors = CryptoJob<KEMEncapsulateTraits>::errors();
147+
if (!out_) {
148+
if (errors->Empty()) errors->Capture();
149+
CHECK(!errors->Empty());
150+
*result = v8::Undefined(env->isolate());
151+
if (!errors->ToException(env).ToLocal(err)) return Nothing<void>();
152+
returnv8::JustVoid();
153+
}
154+
155+
CHECK(errors->Empty());
156+
*err = v8::Undefined(env->isolate());
157+
158+
ByteSource ciphertext = ByteSource::Allocated(out_->ciphertext.release());
159+
ByteSource shared_key = ByteSource::Allocated(out_->shared_key.release());
160+
161+
if (mode() == kCryptoJobWebCrypto) {
162+
Local<Object> output = Object::New(env->isolate());
163+
if (!output
181164
->DefineOwnProperty(env->context(),
182165
OneByteString(env->isolate(), "sharedKey"),
183-
shared_key_obj.As<ArrayBufferView>()->Buffer())
166+
shared_key.ToArrayBuffer(env))
184167
.FromMaybe(false) ||
185-
!result
168+
!output
186169
->DefineOwnProperty(env->context(),
187170
OneByteString(env->isolate(), "ciphertext"),
188-
ciphertext_obj.As<ArrayBufferView>()->Buffer())
171+
ciphertext.ToArrayBuffer(env))
189172
.FromMaybe(false)) {
190-
returnMaybeLocal<Value>();
173+
returnNothing<void>();
191174
}
192-
return result;
175+
*result = output;
176+
returnv8::JustVoid();
193177
}
194178

195-
// Return an array [sharedKey, ciphertext].
196-
Local<Array> result = Array::New(env->isolate(), 2);
197-
if (result->Set(env->context(), 0, shared_key_obj).IsNothing() ||
198-
result->Set(env->context(), 1, ciphertext_obj).IsNothing()) {
199-
returnMaybeLocal<Value>();
179+
Local<Uint8Array> shared_key_buf;
180+
Local<Uint8Array> ciphertext_buf;
181+
if (!shared_key.ToBuffer(env).ToLocal(&shared_key_buf) ||
182+
!ciphertext.ToBuffer(env).ToLocal(&ciphertext_buf)) {
183+
returnNothing<void>();
200184
}
201185

202-
return result;
186+
Local<Array> output = Array::New(env->isolate(), 2);
187+
if (output->Set(env->context(), 0, shared_key_buf).IsNothing() ||
188+
output->Set(env->context(), 1, ciphertext_buf).IsNothing()) {
189+
return Nothing<void>();
190+
}
191+
*result = output;
192+
returnv8::JustVoid();
193+
}
194+
195+
voidKEMEncapsulateJob::MemoryInfo(MemoryTracker* tracker) const {
196+
if (out_) {
197+
tracker->TrackFieldWithSize("ciphertext", out_->ciphertext.size());
198+
tracker->TrackFieldWithSize("shared_key", out_->shared_key.size());
199+
}
200+
CryptoJob<KEMEncapsulateTraits>::MemoryInfo(tracker);
203201
}
204202

205203
// KEMDecapsulateTraits implementation

β€Žsrc/crypto/crypto_kem.hβ€Ž

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -44,15 +44,30 @@ struct KEMEncapsulateTraits final {
4444
const v8::FunctionCallbackInfo<v8::Value>& args,
4545
unsignedint offset,
4646
KEMConfiguration* params);
47+
};
4748

48-
staticboolDeriveBits(Environment* env,
49-
const KEMConfiguration& params,
50-
ByteSource* out,
51-
CryptoJobMode mode);
49+
classKEMEncapsulateJobfinal : public CryptoJob<KEMEncapsulateTraits> {
50+
public:
51+
using AdditionalParams = KEMEncapsulateTraits::AdditionalParameters;
5252

53-
static v8::MaybeLocal<v8::Value> EncodeOutput(Environment* env,
54-
const KEMConfiguration& params,
55-
ByteSource* out);
53+
staticvoidNew(const v8::FunctionCallbackInfo<v8::Value>& args);
54+
staticvoidInitialize(Environment* env, v8::Local<v8::Object> target);
55+
staticvoidRegisterExternalReferences(ExternalReferenceRegistry* registry);
56+
57+
KEMEncapsulateJob(Environment* env,
58+
v8::Local<v8::Object> object,
59+
CryptoJobMode mode,
60+
AdditionalParams&& params);
61+
62+
voidDoThreadPoolWork() override;
63+
v8::Maybe<void> ToResult(v8::Local<v8::Value>* err,
64+
v8::Local<v8::Value>* result) override;
65+
66+
SET_SELF_SIZE(KEMEncapsulateJob)
67+
voidMemoryInfo(MemoryTracker* tracker) constoverride;
68+
69+
private:
70+
std::optional<ncrypto::KEM::EncapsulateResult> out_;
5671
};
5772

5873
structKEMDecapsulateTraitsfinal {
@@ -78,7 +93,6 @@ struct KEMDecapsulateTraits final {
7893
ByteSource* out);
7994
};
8095

81-
using KEMEncapsulateJob = DeriveBitsJob<KEMEncapsulateTraits>;
8296
using KEMDecapsulateJob = DeriveBitsJob<KEMDecapsulateTraits>;
8397

8498
voidInitializeKEM(Environment* env, v8::Local<v8::Object> target);

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 4afc15b

Browse files
panvaaduh95
authored andcommitted
src: avoid redundant KEM encapsulation copies
KEM encapsulation produces separate ciphertext and shared-secret allocations. The existing DeriveBitsJob path packs both values into an intermediate buffer, then copies them again into separate buffers. Instead, this uses a dedicated KEMEncapsulateJob to retain both outputs across the worker boundary and convert each directly through ByteSource. This removes the intermediate allocation and at least one complete round of copies. Signed-off-by: Filip Skokan <panva.ip@gmail.com> PR-URL: #64553 Backport-PR-URL: #65087 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com> Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
1 parent fea0666 commit 4afc15b

2 files changed

Lines changed: 116 additions & 104 deletions

File tree

β€Žsrc/crypto/crypto_kem.ccβ€Ž

Lines changed: 94 additions & 96 deletions
Original file line numberDiff line numberDiff line change
@@ -8,21 +8,20 @@
88
#include"crypto/crypto_util.h"
99
#include"env-inl.h"
1010
#include"memory_tracker-inl.h"
11-
#include"node_buffer.h"
1211
#include"threadpoolwork-inl.h"
1312
#include"v8.h"
1413

1514
namespacenode {
1615

1716
using ncrypto::EVPKeyPointer;
1817
using v8::Array;
19-
using v8::ArrayBufferView;
2018
using v8::FunctionCallbackInfo;
2119
using v8::Local;
2220
using v8::Maybe;
2321
using v8::MaybeLocal;
2422
using v8::Nothing;
2523
using v8::Object;
24+
using v8::Uint8Array;
2625
using v8::Value;
2726

2827
namespacecrypto {
@@ -49,51 +48,6 @@ void KEMConfiguration::MemoryInfo(MemoryTracker* tracker) const {
4948

5049
namespace {
5150

52-
boolDoKEMEncapsulate(Environment* env,
53-
const EVPKeyPointer& public_key,
54-
ByteSource* out,
55-
CryptoJobMode mode) {
56-
auto result = ncrypto::KEM::Encapsulate(public_key);
57-
if (!result) {
58-
if (mode == kCryptoJobSync) {
59-
THROW_ERR_CRYPTO_OPERATION_FAILED(env, "Failed to perform encapsulation");
60-
}
61-
returnfalse;
62-
}
63-
64-
// Pack the result: [ciphertext_len][shared_key_len][ciphertext][shared_key]
65-
size_t ciphertext_len = result->ciphertext.size();
66-
size_t shared_key_len = result->shared_key.size();
67-
size_t total_len =
68-
sizeof(uint32_t) + sizeof(uint32_t) + ciphertext_len + shared_key_len;
69-
70-
auto data = ncrypto::DataPointer::Alloc(total_len);
71-
if (!data) {
72-
if (mode == kCryptoJobSync) {
73-
THROW_ERR_CRYPTO_OPERATION_FAILED(env,
74-
"Failed to allocate output buffer");
75-
}
76-
returnfalse;
77-
}
78-
79-
unsignedchar* ptr = static_cast<unsignedchar*>(data.get());
80-
81-
// Write size headers
82-
*reinterpret_cast<uint32_t*>(ptr) = static_cast<uint32_t>(ciphertext_len);
83-
*reinterpret_cast<uint32_t*>(ptr + sizeof(uint32_t)) =
84-
static_cast<uint32_t>(shared_key_len);
85-
86-
// Write ciphertext and shared key data
87-
unsignedchar* ciphertext_ptr = ptr + 2 * sizeof(uint32_t);
88-
unsignedchar* shared_key_ptr = ciphertext_ptr + ciphertext_len;
89-
90-
std::memcpy(ciphertext_ptr, result->ciphertext.get(), ciphertext_len);
91-
std::memcpy(shared_key_ptr, result->shared_key.get(), shared_key_len);
92-
93-
*out = ByteSource::Allocated(data.release());
94-
returntrue;
95-
}
96-
9751
boolDoKEMDecapsulate(Environment* env,
9852
const EVPKeyPointer& private_key,
9953
const ByteSource& ciphertext,
@@ -135,71 +89,115 @@ Maybe<void> KEMEncapsulateTraits::AdditionalConfig(
13589
returnv8::JustVoid();
13690
}
13791

138-
boolKEMEncapsulateTraits::DeriveBits(Environment* env,
139-
const KEMConfiguration& params,
140-
ByteSource* out,
141-
CryptoJobMode mode) {
142-
Mutex::ScopedLock lock(params.key.mutex());
143-
constauto& public_key = params.key.GetAsymmetricKey();
92+
voidKEMEncapsulateJob::New(const FunctionCallbackInfo<Value>& args) {
93+
Environment* env = Environment::GetCurrent(args);
94+
CHECK(args.IsConstructCall());
95+
96+
CryptoJobMode mode = GetCryptoJobMode(args[0]);
97+
AdditionalParams params;
98+
if (KEMEncapsulateTraits::AdditionalConfig(mode, args, 1, &params)
99+
.IsNothing()) {
100+
return;
101+
}
144102

145-
returnDoKEMEncapsulate(env, public_key, out, mode);
103+
newKEMEncapsulateJob(env, args.This(), mode, std::move(params));
146104
}
147105

148-
MaybeLocal<Value> KEMEncapsulateTraits::EncodeOutput(
149-
Environment* env, const KEMConfiguration& params, ByteSource* out) {
150-
// The output contains:
151-
// [ciphertext_len][shared_key_len][ciphertext][shared_key]
152-
constunsignedchar* data = out->data<unsignedchar>();
153-
154-
uint32_t ciphertext_len = *reinterpret_cast<constuint32_t*>(data);
155-
uint32_t shared_key_len =
156-
*reinterpret_cast<constuint32_t*>(data + sizeof(uint32_t));
157-
158-
constunsignedchar* ciphertext_ptr = data + 2 * sizeof(uint32_t);
159-
constunsignedchar* shared_key_ptr = ciphertext_ptr + ciphertext_len;
160-
161-
MaybeLocal<Object> ciphertext_buf =
162-
node::Buffer::Copy(env->isolate(),
163-
reinterpret_cast<constchar*>(ciphertext_ptr),
164-
ciphertext_len);
165-
166-
MaybeLocal<Object> shared_key_buf =
167-
node::Buffer::Copy(env->isolate(),
168-
reinterpret_cast<constchar*>(shared_key_ptr),
169-
shared_key_len);
170-
171-
Local<Object> ciphertext_obj;
172-
Local<Object> shared_key_obj;
173-
if (!ciphertext_buf.ToLocal(&ciphertext_obj) ||
174-
!shared_key_buf.ToLocal(&shared_key_obj)) {
175-
return MaybeLocal<Value>();
106+
voidKEMEncapsulateJob::Initialize(Environment* env, Local<Object> target) {
107+
CryptoJob<KEMEncapsulateTraits>::Initialize(New, env, target);
108+
}
109+
110+
voidKEMEncapsulateJob::RegisterExternalReferences(
111+
ExternalReferenceRegistry* registry) {
112+
CryptoJob<KEMEncapsulateTraits>::RegisterExternalReferences(New, registry);
113+
}
114+
115+
KEMEncapsulateJob::KEMEncapsulateJob(Environment* env,
116+
Local<Object> object,
117+
CryptoJobMode mode,
118+
AdditionalParams&& params)
119+
: CryptoJob<KEMEncapsulateTraits>(env,
120+
object,
121+
KEMEncapsulateTraits::Provider,
122+
mode,
123+
std::move(params)) {}
124+
125+
voidKEMEncapsulateJob::DoThreadPoolWork() {
126+
ncrypto::ClearErrorOnReturn clear_error_on_return;
127+
AdditionalParams* params = CryptoJob<KEMEncapsulateTraits>::params();
128+
Mutex::ScopedLock lock(params->key.mutex());
129+
out_ = ncrypto::KEM::Encapsulate(params->key.GetAsymmetricKey());
130+
if (!out_) {
131+
if (mode() == kCryptoJobSync) {
132+
THROW_ERR_CRYPTO_OPERATION_FAILED(AsyncWrap::env(),
133+
"Failed to perform encapsulation");
134+
}
135+
CryptoErrorStore* errors = CryptoJob<KEMEncapsulateTraits>::errors();
136+
errors->Capture();
137+
if (errors->Empty()) {
138+
errors->Insert(NodeCryptoError::DERIVING_BITS_FAILED);
139+
}
176140
}
141+
}
177142

178-
if (params.job_mode == kCryptoJobWebCrypto) {
179-
Local<Object> result = Object::New(env->isolate());
180-
if (!result
143+
Maybe<void> KEMEncapsulateJob::ToResult(Local<Value>* err,
144+
Local<Value>* result) {
145+
Environment* env = AsyncWrap::env();
146+
CryptoErrorStore* errors = CryptoJob<KEMEncapsulateTraits>::errors();
147+
if (!out_) {
148+
if (errors->Empty()) errors->Capture();
149+
CHECK(!errors->Empty());
150+
*result = v8::Undefined(env->isolate());
151+
if (!errors->ToException(env).ToLocal(err)) return Nothing<void>();
152+
returnv8::JustVoid();
153+
}
154+
155+
CHECK(errors->Empty());
156+
*err = v8::Undefined(env->isolate());
157+
158+
ByteSource ciphertext = ByteSource::Allocated(out_->ciphertext.release());
159+
ByteSource shared_key = ByteSource::Allocated(out_->shared_key.release());
160+
161+
if (mode() == kCryptoJobWebCrypto) {
162+
Local<Object> output = Object::New(env->isolate());
163+
if (!output
181164
->DefineOwnProperty(env->context(),
182165
OneByteString(env->isolate(), "sharedKey"),
183-
shared_key_obj.As<ArrayBufferView>()->Buffer())
166+
shared_key.ToArrayBuffer(env))
184167
.FromMaybe(false) ||
185-
!result
168+
!output
186169
->DefineOwnProperty(env->context(),
187170
OneByteString(env->isolate(), "ciphertext"),
188-
ciphertext_obj.As<ArrayBufferView>()->Buffer())
171+
ciphertext.ToArrayBuffer(env))
189172
.FromMaybe(false)) {
190-
returnMaybeLocal<Value>();
173+
returnNothing<void>();
191174
}
192-
return result;
175+
*result = output;
176+
returnv8::JustVoid();
193177
}
194178

195-
// Return an array [sharedKey, ciphertext].
196-
Local<Array> result = Array::New(env->isolate(), 2);
197-
if (result->Set(env->context(), 0, shared_key_obj).IsNothing() ||
198-
result->Set(env->context(), 1, ciphertext_obj).IsNothing()) {
199-
returnMaybeLocal<Value>();
179+
Local<Uint8Array> shared_key_buf;
180+
Local<Uint8Array> ciphertext_buf;
181+
if (!shared_key.ToBuffer(env).ToLocal(&shared_key_buf) ||
182+
!ciphertext.ToBuffer(env).ToLocal(&ciphertext_buf)) {
183+
returnNothing<void>();
200184
}
201185

202-
return result;
186+
Local<Array> output = Array::New(env->isolate(), 2);
187+
if (output->Set(env->context(), 0, shared_key_buf).IsNothing() ||
188+
output->Set(env->context(), 1, ciphertext_buf).IsNothing()) {
189+
return Nothing<void>();
190+
}
191+
*result = output;
192+
returnv8::JustVoid();
193+
}
194+
195+
voidKEMEncapsulateJob::MemoryInfo(MemoryTracker* tracker) const {
196+
if (out_) {
197+
tracker->TrackFieldWithSize("ciphertext", out_->ciphertext.size());
198+
tracker->TrackFieldWithSize("shared_key", out_->shared_key.size());
199+
}
200+
CryptoJob<KEMEncapsulateTraits>::MemoryInfo(tracker);
203201
}
204202

205203
// KEMDecapsulateTraits implementation

β€Žsrc/crypto/crypto_kem.hβ€Ž

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -44,15 +44,30 @@ struct KEMEncapsulateTraits final {
4444
const v8::FunctionCallbackInfo<v8::Value>& args,
4545
unsignedint offset,
4646
KEMConfiguration* params);
47+
};
4748

48-
staticboolDeriveBits(Environment* env,
49-
const KEMConfiguration& params,
50-
ByteSource* out,
51-
CryptoJobMode mode);
49+
classKEMEncapsulateJobfinal : public CryptoJob<KEMEncapsulateTraits> {
50+
public:
51+
using AdditionalParams = KEMEncapsulateTraits::AdditionalParameters;
5252

53-
static v8::MaybeLocal<v8::Value> EncodeOutput(Environment* env,
54-
const KEMConfiguration& params,
55-
ByteSource* out);
53+
staticvoidNew(const v8::FunctionCallbackInfo<v8::Value>& args);
54+
staticvoidInitialize(Environment* env, v8::Local<v8::Object> target);
55+
staticvoidRegisterExternalReferences(ExternalReferenceRegistry* registry);
56+
57+
KEMEncapsulateJob(Environment* env,
58+
v8::Local<v8::Object> object,
59+
CryptoJobMode mode,
60+
AdditionalParams&& params);
61+
62+
voidDoThreadPoolWork() override;
63+
v8::Maybe<void> ToResult(v8::Local<v8::Value>* err,
64+
v8::Local<v8::Value>* result) override;
65+
66+
SET_SELF_SIZE(KEMEncapsulateJob)
67+
voidMemoryInfo(MemoryTracker* tracker) constoverride;
68+
69+
private:
70+
std::optional<ncrypto::KEM::EncapsulateResult> out_;
5671
};
5772

5873
structKEMDecapsulateTraitsfinal {
@@ -78,7 +93,6 @@ struct KEMDecapsulateTraits final {
7893
ByteSource* out);
7994
};
8095

81-
using KEMEncapsulateJob = DeriveBitsJob<KEMEncapsulateTraits>;
8296
using KEMDecapsulateJob = DeriveBitsJob<KEMDecapsulateTraits>;
8397

8498
voidInitializeKEM(Environment* env, v8::Local<v8::Object> target);

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Commit 4afc15b

Browse files
panvaaduh95
authored andcommitted
src: avoid redundant KEM encapsulation copies
KEM encapsulation produces separate ciphertext and shared-secret allocations. The existing DeriveBitsJob path packs both values into an intermediate buffer, then copies them again into separate buffers. Instead, this uses a dedicated KEMEncapsulateJob to retain both outputs across the worker boundary and convert each directly through ByteSource. This removes the intermediate allocation and at least one complete round of copies. Signed-off-by: Filip Skokan <panva.ip@gmail.com> PR-URL: #64553 Backport-PR-URL: #65087 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com> Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
1 parent fea0666 commit 4afc15b

2 files changed

Lines changed: 116 additions & 104 deletions

File tree

β€Žsrc/crypto/crypto_kem.ccβ€Ž

Lines changed: 94 additions & 96 deletions
Original file line numberDiff line numberDiff line change
@@ -8,21 +8,20 @@
88
#include"crypto/crypto_util.h"
99
#include"env-inl.h"
1010
#include"memory_tracker-inl.h"
11-
#include"node_buffer.h"
1211
#include"threadpoolwork-inl.h"
1312
#include"v8.h"
1413

1514
namespacenode {
1615

1716
using ncrypto::EVPKeyPointer;
1817
using v8::Array;
19-
using v8::ArrayBufferView;
2018
using v8::FunctionCallbackInfo;
2119
using v8::Local;
2220
using v8::Maybe;
2321
using v8::MaybeLocal;
2422
using v8::Nothing;
2523
using v8::Object;
24+
using v8::Uint8Array;
2625
using v8::Value;
2726

2827
namespacecrypto {
@@ -49,51 +48,6 @@ void KEMConfiguration::MemoryInfo(MemoryTracker* tracker) const {
4948

5049
namespace {
5150

52-
boolDoKEMEncapsulate(Environment* env,
53-
const EVPKeyPointer& public_key,
54-
ByteSource* out,
55-
CryptoJobMode mode) {
56-
auto result = ncrypto::KEM::Encapsulate(public_key);
57-
if (!result) {
58-
if (mode == kCryptoJobSync) {
59-
THROW_ERR_CRYPTO_OPERATION_FAILED(env, "Failed to perform encapsulation");
60-
}
61-
returnfalse;
62-
}
63-
64-
// Pack the result: [ciphertext_len][shared_key_len][ciphertext][shared_key]
65-
size_t ciphertext_len = result->ciphertext.size();
66-
size_t shared_key_len = result->shared_key.size();
67-
size_t total_len =
68-
sizeof(uint32_t) + sizeof(uint32_t) + ciphertext_len + shared_key_len;
69-
70-
auto data = ncrypto::DataPointer::Alloc(total_len);
71-
if (!data) {
72-
if (mode == kCryptoJobSync) {
73-
THROW_ERR_CRYPTO_OPERATION_FAILED(env,
74-
"Failed to allocate output buffer");
75-
}
76-
returnfalse;
77-
}
78-
79-
unsignedchar* ptr = static_cast<unsignedchar*>(data.get());
80-
81-
// Write size headers
82-
*reinterpret_cast<uint32_t*>(ptr) = static_cast<uint32_t>(ciphertext_len);
83-
*reinterpret_cast<uint32_t*>(ptr + sizeof(uint32_t)) =
84-
static_cast<uint32_t>(shared_key_len);
85-
86-
// Write ciphertext and shared key data
87-
unsignedchar* ciphertext_ptr = ptr + 2 * sizeof(uint32_t);
88-
unsignedchar* shared_key_ptr = ciphertext_ptr + ciphertext_len;
89-
90-
std::memcpy(ciphertext_ptr, result->ciphertext.get(), ciphertext_len);
91-
std::memcpy(shared_key_ptr, result->shared_key.get(), shared_key_len);
92-
93-
*out = ByteSource::Allocated(data.release());
94-
returntrue;
95-
}
96-
9751
boolDoKEMDecapsulate(Environment* env,
9852
const EVPKeyPointer& private_key,
9953
const ByteSource& ciphertext,
@@ -135,71 +89,115 @@ Maybe<void> KEMEncapsulateTraits::AdditionalConfig(
13589
returnv8::JustVoid();
13690
}
13791

138-
boolKEMEncapsulateTraits::DeriveBits(Environment* env,
139-
const KEMConfiguration& params,
140-
ByteSource* out,
141-
CryptoJobMode mode) {
142-
Mutex::ScopedLock lock(params.key.mutex());
143-
constauto& public_key = params.key.GetAsymmetricKey();
92+
voidKEMEncapsulateJob::New(const FunctionCallbackInfo<Value>& args) {
93+
Environment* env = Environment::GetCurrent(args);
94+
CHECK(args.IsConstructCall());
95+
96+
CryptoJobMode mode = GetCryptoJobMode(args[0]);
97+
AdditionalParams params;
98+
if (KEMEncapsulateTraits::AdditionalConfig(mode, args, 1, &params)
99+
.IsNothing()) {
100+
return;
101+
}
144102

145-
returnDoKEMEncapsulate(env, public_key, out, mode);
103+
newKEMEncapsulateJob(env, args.This(), mode, std::move(params));
146104
}
147105

148-
MaybeLocal<Value> KEMEncapsulateTraits::EncodeOutput(
149-
Environment* env, const KEMConfiguration& params, ByteSource* out) {
150-
// The output contains:
151-
// [ciphertext_len][shared_key_len][ciphertext][shared_key]
152-
constunsignedchar* data = out->data<unsignedchar>();
153-
154-
uint32_t ciphertext_len = *reinterpret_cast<constuint32_t*>(data);
155-
uint32_t shared_key_len =
156-
*reinterpret_cast<constuint32_t*>(data + sizeof(uint32_t));
157-
158-
constunsignedchar* ciphertext_ptr = data + 2 * sizeof(uint32_t);
159-
constunsignedchar* shared_key_ptr = ciphertext_ptr + ciphertext_len;
160-
161-
MaybeLocal<Object> ciphertext_buf =
162-
node::Buffer::Copy(env->isolate(),
163-
reinterpret_cast<constchar*>(ciphertext_ptr),
164-
ciphertext_len);
165-
166-
MaybeLocal<Object> shared_key_buf =
167-
node::Buffer::Copy(env->isolate(),
168-
reinterpret_cast<constchar*>(shared_key_ptr),
169-
shared_key_len);
170-
171-
Local<Object> ciphertext_obj;
172-
Local<Object> shared_key_obj;
173-
if (!ciphertext_buf.ToLocal(&ciphertext_obj) ||
174-
!shared_key_buf.ToLocal(&shared_key_obj)) {
175-
return MaybeLocal<Value>();
106+
voidKEMEncapsulateJob::Initialize(Environment* env, Local<Object> target) {
107+
CryptoJob<KEMEncapsulateTraits>::Initialize(New, env, target);
108+
}
109+
110+
voidKEMEncapsulateJob::RegisterExternalReferences(
111+
ExternalReferenceRegistry* registry) {
112+
CryptoJob<KEMEncapsulateTraits>::RegisterExternalReferences(New, registry);
113+
}
114+
115+
KEMEncapsulateJob::KEMEncapsulateJob(Environment* env,
116+
Local<Object> object,
117+
CryptoJobMode mode,
118+
AdditionalParams&& params)
119+
: CryptoJob<KEMEncapsulateTraits>(env,
120+
object,
121+
KEMEncapsulateTraits::Provider,
122+
mode,
123+
std::move(params)) {}
124+
125+
voidKEMEncapsulateJob::DoThreadPoolWork() {
126+
ncrypto::ClearErrorOnReturn clear_error_on_return;
127+
AdditionalParams* params = CryptoJob<KEMEncapsulateTraits>::params();
128+
Mutex::ScopedLock lock(params->key.mutex());
129+
out_ = ncrypto::KEM::Encapsulate(params->key.GetAsymmetricKey());
130+
if (!out_) {
131+
if (mode() == kCryptoJobSync) {
132+
THROW_ERR_CRYPTO_OPERATION_FAILED(AsyncWrap::env(),
133+
"Failed to perform encapsulation");
134+
}
135+
CryptoErrorStore* errors = CryptoJob<KEMEncapsulateTraits>::errors();
136+
errors->Capture();
137+
if (errors->Empty()) {
138+
errors->Insert(NodeCryptoError::DERIVING_BITS_FAILED);
139+
}
176140
}
141+
}
177142

178-
if (params.job_mode == kCryptoJobWebCrypto) {
179-
Local<Object> result = Object::New(env->isolate());
180-
if (!result
143+
Maybe<void> KEMEncapsulateJob::ToResult(Local<Value>* err,
144+
Local<Value>* result) {
145+
Environment* env = AsyncWrap::env();
146+
CryptoErrorStore* errors = CryptoJob<KEMEncapsulateTraits>::errors();
147+
if (!out_) {
148+
if (errors->Empty()) errors->Capture();
149+
CHECK(!errors->Empty());
150+
*result = v8::Undefined(env->isolate());
151+
if (!errors->ToException(env).ToLocal(err)) return Nothing<void>();
152+
returnv8::JustVoid();
153+
}
154+
155+
CHECK(errors->Empty());
156+
*err = v8::Undefined(env->isolate());
157+
158+
ByteSource ciphertext = ByteSource::Allocated(out_->ciphertext.release());
159+
ByteSource shared_key = ByteSource::Allocated(out_->shared_key.release());
160+
161+
if (mode() == kCryptoJobWebCrypto) {
162+
Local<Object> output = Object::New(env->isolate());
163+
if (!output
181164
->DefineOwnProperty(env->context(),
182165
OneByteString(env->isolate(), "sharedKey"),
183-
shared_key_obj.As<ArrayBufferView>()->Buffer())
166+
shared_key.ToArrayBuffer(env))
184167
.FromMaybe(false) ||
185-
!result
168+
!output
186169
->DefineOwnProperty(env->context(),
187170
OneByteString(env->isolate(), "ciphertext"),
188-
ciphertext_obj.As<ArrayBufferView>()->Buffer())
171+
ciphertext.ToArrayBuffer(env))
189172
.FromMaybe(false)) {
190-
returnMaybeLocal<Value>();
173+
returnNothing<void>();
191174
}
192-
return result;
175+
*result = output;
176+
returnv8::JustVoid();
193177
}
194178

195-
// Return an array [sharedKey, ciphertext].
196-
Local<Array> result = Array::New(env->isolate(), 2);
197-
if (result->Set(env->context(), 0, shared_key_obj).IsNothing() ||
198-
result->Set(env->context(), 1, ciphertext_obj).IsNothing()) {
199-
returnMaybeLocal<Value>();
179+
Local<Uint8Array> shared_key_buf;
180+
Local<Uint8Array> ciphertext_buf;
181+
if (!shared_key.ToBuffer(env).ToLocal(&shared_key_buf) ||
182+
!ciphertext.ToBuffer(env).ToLocal(&ciphertext_buf)) {
183+
returnNothing<void>();
200184
}
201185

202-
return result;
186+
Local<Array> output = Array::New(env->isolate(), 2);
187+
if (output->Set(env->context(), 0, shared_key_buf).IsNothing() ||
188+
output->Set(env->context(), 1, ciphertext_buf).IsNothing()) {
189+
return Nothing<void>();
190+
}
191+
*result = output;
192+
returnv8::JustVoid();
193+
}
194+
195+
voidKEMEncapsulateJob::MemoryInfo(MemoryTracker* tracker) const {
196+
if (out_) {
197+
tracker->TrackFieldWithSize("ciphertext", out_->ciphertext.size());
198+
tracker->TrackFieldWithSize("shared_key", out_->shared_key.size());
199+
}
200+
CryptoJob<KEMEncapsulateTraits>::MemoryInfo(tracker);
203201
}
204202

205203
// KEMDecapsulateTraits implementation

β€Žsrc/crypto/crypto_kem.hβ€Ž

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -44,15 +44,30 @@ struct KEMEncapsulateTraits final {
4444
const v8::FunctionCallbackInfo<v8::Value>& args,
4545
unsignedint offset,
4646
KEMConfiguration* params);
47+
};
4748

48-
staticboolDeriveBits(Environment* env,
49-
const KEMConfiguration& params,
50-
ByteSource* out,
51-
CryptoJobMode mode);
49+
classKEMEncapsulateJobfinal : public CryptoJob<KEMEncapsulateTraits> {
50+
public:
51+
using AdditionalParams = KEMEncapsulateTraits::AdditionalParameters;
5252

53-
static v8::MaybeLocal<v8::Value> EncodeOutput(Environment* env,
54-
const KEMConfiguration& params,
55-
ByteSource* out);
53+
staticvoidNew(const v8::FunctionCallbackInfo<v8::Value>& args);
54+
staticvoidInitialize(Environment* env, v8::Local<v8::Object> target);
55+
staticvoidRegisterExternalReferences(ExternalReferenceRegistry* registry);
56+
57+
KEMEncapsulateJob(Environment* env,
58+
v8::Local<v8::Object> object,
59+
CryptoJobMode mode,
60+
AdditionalParams&& params);
61+
62+
voidDoThreadPoolWork() override;
63+
v8::Maybe<void> ToResult(v8::Local<v8::Value>* err,
64+
v8::Local<v8::Value>* result) override;
65+
66+
SET_SELF_SIZE(KEMEncapsulateJob)
67+
voidMemoryInfo(MemoryTracker* tracker) constoverride;
68+
69+
private:
70+
std::optional<ncrypto::KEM::EncapsulateResult> out_;
5671
};
5772

5873
structKEMDecapsulateTraitsfinal {
@@ -78,7 +93,6 @@ struct KEMDecapsulateTraits final {
7893
ByteSource* out);
7994
};
8095

81-
using KEMEncapsulateJob = DeriveBitsJob<KEMEncapsulateTraits>;
8296
using KEMDecapsulateJob = DeriveBitsJob<KEMDecapsulateTraits>;
8397

8498
voidInitializeKEM(Environment* env, v8::Local<v8::Object> target);

0 commit comments

Comments
Β (0)