Skip to content

Commit

Permalink
crypto: harden bignum-to-binary conversions
Browse files Browse the repository at this point in the history
PR-URL: #24719
Refs: #24645
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
  • Loading branch information
bnoordhuis authored and BridgeAR committed Dec 5, 2018
1 parent 6b71099 commit 12feb9e
Showing 1 changed file with 10 additions and 10 deletions.
20 changes: 10 additions & 10 deletions src/node_crypto.cc
Original file line number Diff line number Diff line change
Expand Up @@ -4186,9 +4186,11 @@ void DiffieHellman::GenerateKeys(const FunctionCallbackInfo<Value>& 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<unsigned char*>(data));
CHECK_EQ(size,
BN_bn2binpad(pub_key, reinterpret_cast<unsigned char*>(data), size));
args.GetReturnValue().Set(Buffer::New(env, data, size).ToLocalChecked());
}

Expand All @@ -4204,9 +4206,11 @@ void DiffieHellman::GetField(const FunctionCallbackInfo<Value>& 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<unsigned char*>(data));
CHECK_EQ(size,
BN_bn2binpad(num, reinterpret_cast<unsigned char*>(data), size));
args.GetReturnValue().Set(Buffer::New(env, data, size).ToLocalChecked());
}

Expand Down Expand Up @@ -4542,13 +4546,9 @@ void ECDH::GetPrivateKey(const FunctionCallbackInfo<Value>& 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<unsigned char>(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<Object> buf =
Buffer::New(env, reinterpret_cast<char*>(out), size).ToLocalChecked();
Expand Down

0 comments on commit 12feb9e

Please sign in to comment.