Skip to content

Commit 1f54fc2

Browse files
authored
src: use automatic memory mgmt in SecretKeyGen
Avoid manual memory management (i.e., calling MallocOpenSSL). This leaves less room for memory leaks and other bugs. PR-URL: #44479 Reviewed-By: Anna Henningsen <[email protected]> Reviewed-By: Ben Noordhuis <[email protected]>
1 parent 03553c5 commit 1f54fc2

File tree

2 files changed

+9
-11
lines changed

2 files changed

+9
-11
lines changed

src/crypto/crypto_keygen.cc

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -54,8 +54,7 @@ EVPKeyCtxPointer NidKeyPairGenTraits::Setup(NidKeyPairGenConfig* params) {
5454
}
5555

5656
void SecretKeyGenConfig::MemoryInfo(MemoryTracker* tracker) const {
57-
if (out != nullptr)
58-
tracker->TrackFieldWithSize("out", length);
57+
if (out) tracker->TrackFieldWithSize("out", length);
5958
}
6059

6160
Maybe<bool> SecretKeyGenTraits::AdditionalConfig(
@@ -80,18 +79,17 @@ KeyGenJobStatus SecretKeyGenTraits::DoKeyGen(
8079
Environment* env,
8180
SecretKeyGenConfig* params) {
8281
CHECK_LE(params->length, INT_MAX);
83-
params->out = MallocOpenSSL<char>(params->length);
84-
EntropySource(reinterpret_cast<unsigned char*>(params->out), params->length);
82+
ByteSource::Builder bytes(params->length);
83+
EntropySource(bytes.data<unsigned char>(), params->length);
84+
params->out = std::move(bytes).release();
8585
return KeyGenJobStatus::OK;
8686
}
8787

88-
Maybe<bool> SecretKeyGenTraits::EncodeKey(
89-
Environment* env,
90-
SecretKeyGenConfig* params,
91-
Local<Value>* result) {
92-
ByteSource out = ByteSource::Allocated(params->out, params->length);
88+
Maybe<bool> SecretKeyGenTraits::EncodeKey(Environment* env,
89+
SecretKeyGenConfig* params,
90+
Local<Value>* result) {
9391
std::shared_ptr<KeyObjectData> data =
94-
KeyObjectData::CreateSecret(std::move(out));
92+
KeyObjectData::CreateSecret(std::move(params->out));
9593
return Just(KeyObjectHandle::Create(env, data).ToLocal(result));
9694
}
9795

src/crypto/crypto_keygen.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -201,7 +201,7 @@ struct KeyPairGenTraits final {
201201

202202
struct SecretKeyGenConfig final : public MemoryRetainer {
203203
size_t length; // In bytes.
204-
char* out = nullptr; // Placeholder for the generated key bytes.
204+
ByteSource out; // Placeholder for the generated key bytes.
205205

206206
void MemoryInfo(MemoryTracker* tracker) const override;
207207
SET_MEMORY_INFO_NAME(SecretKeyGenConfig)

0 commit comments

Comments
 (0)