diff --git a/src/node_crypto.cc b/src/node_crypto.cc index 1027f5f760a56a..295aaa8e14937d 100644 --- a/src/node_crypto.cc +++ b/src/node_crypto.cc @@ -4115,9 +4115,11 @@ void DiffieHellman::GenerateKeys(const FunctionCallbackInfo& args) { const BIGNUM* pub_key; DH_get0_key(diffieHellman->dh_.get(), &pub_key, nullptr); - size_t size = BN_num_bytes(pub_key); + const int size = BN_num_bytes(pub_key); + CHECK_GE(size, 0); char* data = Malloc(size); - BN_bn2bin(pub_key, reinterpret_cast(data)); + CHECK_EQ(size, + BN_bn2binpad(pub_key, reinterpret_cast(data), size)); args.GetReturnValue().Set(Buffer::New(env, data, size).ToLocalChecked()); } @@ -4133,9 +4135,11 @@ void DiffieHellman::GetField(const FunctionCallbackInfo& args, const BIGNUM* num = get_field(dh->dh_.get()); if (num == nullptr) return env->ThrowError(err_if_null); - size_t size = BN_num_bytes(num); + const int size = BN_num_bytes(num); + CHECK_GE(size, 0); char* data = Malloc(size); - BN_bn2bin(num, reinterpret_cast(data)); + CHECK_EQ(size, + BN_bn2binpad(num, reinterpret_cast(data), size)); args.GetReturnValue().Set(Buffer::New(env, data, size).ToLocalChecked()); } @@ -4470,13 +4474,9 @@ void ECDH::GetPrivateKey(const FunctionCallbackInfo& args) { if (b == nullptr) return env->ThrowError("Failed to get ECDH private key"); - int size = BN_num_bytes(b); + const int size = BN_num_bytes(b); unsigned char* out = node::Malloc(size); - - if (size != BN_bn2bin(b, out)) { - free(out); - return env->ThrowError("Failed to convert ECDH private key to Buffer"); - } + CHECK_EQ(size, BN_bn2binpad(b, out, size)); Local buf = Buffer::New(env, reinterpret_cast(out), size).ToLocalChecked();