src: reduce allocations in exportPublicKey()

PR-URL: https://github.com/nodejs/node/pull/14122
Reviewed-By: Anna Henningsen <anna@addaleax.net>
Reviewed-By: James M Snell <jasnell@gmail.com>
This commit is contained in:
Ben Noordhuis 2017-07-10 12:56:37 +02:00
parent ed2a7fbcfe
commit 58926d4075

View File

@ -5835,7 +5835,7 @@ void VerifySpkac(const FunctionCallbackInfo<Value>& args) {
} }
const char* ExportPublicKey(const char* data, int len) { char* ExportPublicKey(const char* data, int len, size_t* size) {
char* buf = nullptr; char* buf = nullptr;
EVP_PKEY* pkey = nullptr; EVP_PKEY* pkey = nullptr;
NETSCAPE_SPKI* spki = nullptr; NETSCAPE_SPKI* spki = nullptr;
@ -5855,12 +5855,12 @@ const char* ExportPublicKey(const char* data, int len) {
if (PEM_write_bio_PUBKEY(bio, pkey) <= 0) if (PEM_write_bio_PUBKEY(bio, pkey) <= 0)
goto exit; goto exit;
BIO_write(bio, "\0", 1);
BUF_MEM* ptr; BUF_MEM* ptr;
BIO_get_mem_ptr(bio, &ptr); BIO_get_mem_ptr(bio, &ptr);
buf = new char[ptr->length]; *size = ptr->length;
memcpy(buf, ptr->data, ptr->length); buf = Malloc(*size);
memcpy(buf, ptr->data, *size);
exit: exit:
if (pkey != nullptr) if (pkey != nullptr)
@ -5891,14 +5891,12 @@ void ExportPublicKey(const FunctionCallbackInfo<Value>& args) {
char* data = Buffer::Data(args[0]); char* data = Buffer::Data(args[0]);
CHECK_NE(data, nullptr); CHECK_NE(data, nullptr);
const char* pkey = ExportPublicKey(data, length); size_t pkey_size;
char* pkey = ExportPublicKey(data, length, &pkey_size);
if (pkey == nullptr) if (pkey == nullptr)
return args.GetReturnValue().SetEmptyString(); return args.GetReturnValue().SetEmptyString();
Local<Value> out = Encode(env->isolate(), pkey, strlen(pkey), BUFFER); Local<Value> out = Buffer::New(env, pkey, pkey_size).ToLocalChecked();
delete[] pkey;
args.GetReturnValue().Set(out); args.GetReturnValue().Set(out);
} }