Skip to content

Commit

Permalink
crypto: input typechecking
Browse files Browse the repository at this point in the history
Handle input typechecking in JavaScript using
errors. Minor fixes and updated tests
  • Loading branch information
wuweiweiwu committed Mar 10, 2018
1 parent d5f07d9 commit c201c26
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 10 deletions.
9 changes: 9 additions & 0 deletions lib/internal/crypto/diffiehellman.js
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,15 @@ ECDH.prototype.getPublicKey = function getPublicKey(encoding, format) {
};

ECDH.convertKey = function convertKey(key, curve, inEnc, outEnc, format) {
if (typeof key !== 'string' && !isArrayBufferView(key)) {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'key',
['string', 'Buffer', 'TypedArray', 'DataView']);
}

if (typeof curve !== 'string') {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'curve', 'string');
}

const encoding = getDefaultEncoding();
inEnc = inEnc || encoding;
outEnc = outEnc || encoding;
Expand Down
3 changes: 0 additions & 3 deletions src/node_crypto.cc
Original file line number Diff line number Diff line change
Expand Up @@ -5561,13 +5561,10 @@ void ConvertKey(const FunctionCallbackInfo<Value>& args) {

CHECK_EQ(args.Length(), 3);

THROW_AND_RETURN_IF_NOT_BUFFER(args[0], "Public key");

size_t len = Buffer::Length(args[0]);
if (len == 0)
return args.GetReturnValue().SetEmptyString();

THROW_AND_RETURN_IF_NOT_STRING(args[1], "ECDH curve name");
node::Utf8Value curve(env->isolate(), args[1]);

int nid = OBJ_sn2nid(*curve);
Expand Down
11 changes: 4 additions & 7 deletions test/parallel/test-crypto-ecdh-convert-key.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,8 @@ if (!common.hasCrypto)
common.skip('missing crypto');

const assert = require('assert');
const crypto = require('crypto');

const { ECDH, getCurves } = crypto;
const { ECDH, getCurves } = require('crypto');

// A valid private key for the secp256k1 curve.
const cafebabeKey = 'cafebabe'.repeat(8);
Expand All @@ -21,16 +20,16 @@ const cafebabePubPtUnComp =
common.expectsError(
() => ECDH.convertKey(),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
message: 'Public key must be a buffer'
});

// Invalid test: curve argument is undefined.
common.expectsError(
() => ECDH.convertKey(cafebabePubPtComp),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError,
message: 'ECDH curve name must be a string'
});

// Invalid test: curve argument is invalid.
Expand All @@ -41,9 +40,7 @@ common.expectsError(
message: 'Invalid ECDH curve name'
});

const availableCurves = new Set(getCurves());

if (availableCurves.has('secp256k1')) {
if (getCurves().includes('secp256k1')) {
// Invalid test: format argument is undefined.
common.expectsError(
() => ECDH.convertKey(cafebabePubPtComp, 'secp256k1', 'hex', 'hex', 10),
Expand Down

0 comments on commit c201c26

Please sign in to comment.