Skip to content

crypto: multiple webcrypto fixes #43431

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Closed
wants to merge 5 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions lib/internal/crypto/aes.js
Original file line number Diff line number Diff line change
@@ -230,13 +230,17 @@ async function aesGenerateKey(algorithm, extractable, keyUsages) {
validateInteger(length, 'algorithm.length');
validateOneOf(length, 'algorithm.length', kAesKeyLengths);

const usageSet = new SafeSet(keyUsages);
const checkUsages = ['wrapKey', 'unwrapKey'];
if (name !== 'AES-KW')
ArrayPrototypePush(checkUsages, 'encrypt', 'decrypt');

if (hasAnyNotIn(usageSet, ['encrypt', 'decrypt', 'wrapKey', 'unwrapKey'])) {
const usagesSet = new SafeSet(keyUsages);
if (hasAnyNotIn(usagesSet, checkUsages)) {
throw lazyDOMException(
'Unsupported key usage for an AES key',
'SyntaxError');
}

return new Promise((resolve, reject) => {
generateKey('aes', { length }, (err, key) => {
if (err) {
@@ -249,7 +253,7 @@ async function aesGenerateKey(algorithm, extractable, keyUsages) {
resolve(new InternalCryptoKey(
key,
{ name, length },
ArrayFrom(usageSet),
ArrayFrom(usagesSet),
extractable));
});
});
8 changes: 4 additions & 4 deletions lib/internal/crypto/diffiehellman.js
Original file line number Diff line number Diff line change
@@ -3,7 +3,7 @@
const {
ArrayBufferPrototypeSlice,
FunctionPrototypeCall,
MathFloor,
MathCeil,
ObjectDefineProperty,
Promise,
SafeSet,
@@ -386,9 +386,9 @@ async function asyncDeriveBitsECDH(algorithm, baseKey, length) {
if (length === null)
return bits;

// If the length is not a multiple of 8, it will be truncated
// down to the nearest multiple of 8.
length = MathFloor(length / 8);
// If the length is not a multiple of 8 the nearest ceiled
// multiple of 8 is sliced.
length = MathCeil(length / 8);
const { byteLength } = bits;

// If the length is larger than the derived secret, throw.
25 changes: 20 additions & 5 deletions lib/internal/crypto/hash.js
Original file line number Diff line number Diff line change
@@ -28,6 +28,10 @@ const {
prepareSecretKey,
} = require('internal/crypto/keys');

const {
lazyDOMException,
} = require('internal/util');

const {
Buffer,
} = require('buffer');
@@ -171,11 +175,22 @@ async function asyncDigest(algorithm, data) {
if (algorithm.length !== undefined)
validateUint32(algorithm.length, 'algorithm.length');

return jobPromise(new HashJob(
kCryptoJobAsync,
normalizeHashName(algorithm.name),
data,
algorithm.length));
switch (algorithm.name) {
case 'SHA-1':
// Fall through
case 'SHA-256':
// Fall through
case 'SHA-384':
// Fall through
case 'SHA-512':
return jobPromise(new HashJob(
kCryptoJobAsync,
normalizeHashName(algorithm.name),
data,
algorithm.length));
}

throw lazyDOMException('Unrecognized name.', 'NotSupportedError');
}

module.exports = {
2 changes: 1 addition & 1 deletion lib/internal/crypto/rsa.js
Original file line number Diff line number Diff line change
@@ -176,7 +176,7 @@ async function rsaKeyGenerate(
return new Promise((resolve, reject) => {
generateKeyPair('rsa', {
modulusLength,
publicExponentConverted,
publicExponent: publicExponentConverted,
}, (err, pubKey, privKey) => {
if (err) {
return reject(lazyDOMException(
5 changes: 5 additions & 0 deletions lib/internal/crypto/webcrypto.js
Original file line number Diff line number Diff line change
@@ -89,6 +89,11 @@ async function generateKey(
algorithm = normalizeAlgorithm(algorithm);
validateBoolean(extractable, 'extractable');
validateArray(keyUsages, 'keyUsages');
if (keyUsages.length === 0) {
throw lazyDOMException(
'Usages cannot be empty when creating a key',
'SyntaxError');
}
switch (algorithm.name) {
case 'RSASSA-PKCS1-v1_5':
// Fall through
2 changes: 1 addition & 1 deletion test/parallel/test-webcrypto-derivebits-cfrg.js
Original file line number Diff line number Diff line change
@@ -133,7 +133,7 @@ async function prepareKeys() {

assert.strictEqual(
Buffer.from(bits).toString('hex'),
result.slice(0, -4));
result.slice(0, -2));
}
}));

2 changes: 1 addition & 1 deletion test/parallel/test-webcrypto-derivebits-ecdh.js
Original file line number Diff line number Diff line change
@@ -154,7 +154,7 @@ async function prepareKeys() {

assert.strictEqual(
Buffer.from(bits).toString('hex'),
result.slice(0, -4));
result.slice(0, -2));
}
}));

6 changes: 6 additions & 0 deletions test/parallel/test-webcrypto-digest.js
Original file line number Diff line number Diff line change
@@ -168,3 +168,9 @@ async function testDigest(size, name) {

await Promise.all(variations);
})().then(common.mustCall());

(async () => {
await assert.rejects(subtle.digest('RSA-OAEP', Buffer.alloc(1)), {
name: 'NotSupportedError',
});
})().then(common.mustCall());
Comment on lines +172 to +176
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: the async wrapper is technically not needed (although it's fine to keep it if you prefer as is)

Suggested change
(async () => {
await assert.rejects(subtle.digest('RSA-OAEP', Buffer.alloc(1)), {
name: 'NotSupportedError',
});
})().then(common.mustCall());
assert.rejects(subtle.digest('RSA-OAEP', Buffer.alloc(1)), {
name: 'NotSupportedError',
}).then(common.mustCall());

48 changes: 40 additions & 8 deletions test/parallel/test-webcrypto-keygen.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// Flags: --expose-internals
'use strict';

const common = require('../common');
@@ -10,8 +11,11 @@ const { types: { isCryptoKey } } = require('util');
const {
webcrypto: { subtle, CryptoKey },
createSecretKey,
KeyObject,
} = require('crypto');

const { bigIntArrayToUnsignedBigInt } = require('internal/crypto/util');

const allUsages = [
'encrypt',
'decrypt',
@@ -206,19 +210,30 @@ const vectors = {
// Test bad usages
{
async function test(name) {
const invalidUsages = [];
allUsages.forEach((usage) => {
if (!vectors[name].usages.includes(usage))
invalidUsages.push(usage);
});
return assert.rejects(
await assert.rejects(
subtle.generateKey(
{
name, ...vectors[name].algorithm
},
true,
invalidUsages),
{ message: /Unsupported key usage/ });
[]),
{ message: /Usages cannot be empty/ });

const invalidUsages = [];
allUsages.forEach((usage) => {
if (!vectors[name].usages.includes(usage))
invalidUsages.push(usage);
});
for (const invalidUsage of invalidUsages) {
await assert.rejects(
subtle.generateKey(
{
name, ...vectors[name].algorithm
},
true,
[...vectors[name].usages, invalidUsage]),
{ message: /Unsupported key usage/ });
}
}

const tests = Object.keys(vectors).map(test);
@@ -262,10 +277,16 @@ const vectors = {
assert.strictEqual(publicKey.algorithm.name, name);
assert.strictEqual(publicKey.algorithm.modulusLength, modulusLength);
assert.deepStrictEqual(publicKey.algorithm.publicExponent, publicExponent);
assert.strictEqual(
KeyObject.from(publicKey).asymmetricKeyDetails.publicExponent,
bigIntArrayToUnsignedBigInt(publicExponent));
assert.strictEqual(publicKey.algorithm.hash.name, hash);
assert.strictEqual(privateKey.algorithm.name, name);
assert.strictEqual(privateKey.algorithm.modulusLength, modulusLength);
assert.deepStrictEqual(privateKey.algorithm.publicExponent, publicExponent);
assert.strictEqual(
KeyObject.from(privateKey).asymmetricKeyDetails.publicExponent,
bigIntArrayToUnsignedBigInt(publicExponent));
assert.strictEqual(privateKey.algorithm.hash.name, hash);

// Missing parameters
@@ -342,6 +363,17 @@ const vectors = {
code: 'ERR_INVALID_ARG_TYPE'
});
}));

await Promise.all([[1], [1, 0, 0]].map((publicExponent) => {
return assert.rejects(subtle.generateKey({
name,
modulusLength,
publicExponent: new Uint8Array(publicExponent),
hash
}, true, usages), {
name: 'OperationError',
});
}));
}

const kTests = [
2 changes: 1 addition & 1 deletion test/parallel/test-webcrypto-sign-verify-hmac.js
Original file line number Diff line number Diff line change
@@ -153,7 +153,7 @@ async function testSign({ hash,
}

await assert.rejects(
subtle.generateKey({ name }, false, []), {
subtle.generateKey({ name }, false, ['sign', 'verify']), {
name: 'TypeError',
code: 'ERR_MISSING_OPTION',
message: 'algorithm.hash is required'