crypto: add SHAKE Web Cryptography digest algorithms

PR-URL: https://github.com/nodejs/node/pull/59365
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Ethan Arrowood <ethan@arrowood.dev>
Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com>
Reviewed-By: Joyee Cheung <joyeec9h3@gmail.com>
This commit is contained in:
Filip Skokan authored and Michaël Zasso committed 2025-08-21 19:01:08 +02:00
1 parent f4fbcca5ce
commit 247d017501
12 files changed
+197 -46

No files matched your search

+61 -1
View File
@@ -2,6 +2,9 @@
<!-- YAML
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/59365
description: SHAKE algorithms are now supported.
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/59365
description: ML-DSA algorithms are now supported.
@@ -91,6 +94,8 @@ WICG proposal:
Algorithms:
* `'cSHAKE128'`
* `'cSHAKE256'`
* `'ML-DSA-44'`[^openssl35]
* `'ML-DSA-65'`[^openssl35]
* `'ML-DSA-87'`[^openssl35]
@@ -472,6 +477,8 @@ implementation and the APIs supported for each:
| `'AES-CTR'` | ✔ | ✔ | ✔ | ✔ | ✔ | ✔ | ✔ | | | | | |
| `'AES-GCM'` | ✔ | ✔ | ✔ | ✔ | ✔ | ✔ | ✔ | | | | | |
| `'AES-KW'` | ✔ | ✔ | ✔ | | | ✔ | ✔ | | | | | |
| `'cSHAKE128'`[^modern-algos] | | | | | | | | | | | | ✔ |
| `'cSHAKE256'`[^modern-algos] | | | | | | | | | | | | ✔ |
| `'ECDH'` | ✔ | ✔ | ✔ | | | | | ✔ | ✔ | | | |
| `'ECDSA'` | ✔ | ✔ | ✔ | | | | | | | ✔ | ✔ | |
| `'Ed25519'` | ✔ | ✔ | ✔ | | | | | | | ✔ | ✔ | |
@@ -800,9 +807,13 @@ The algorithms currently supported include:
<!-- YAML
added: v15.0.0
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/59365
description: SHAKE algorithms are now supported.
-->
* `algorithm` {string|Algorithm}
* `algorithm` {string|Algorithm|CShakeParams}
* `data` {ArrayBuffer|TypedArray|DataView|Buffer}
* Returns: {Promise} Fulfills with an {ArrayBuffer} upon success.
@@ -812,6 +823,8 @@ with an {ArrayBuffer} containing the computed digest.
If `algorithm` is provided as a {string}, it must be one of:
* `'cSHAKE128'`[^modern-algos]
* `'cSHAKE256'`[^modern-algos]
* `'SHA-1'`
* `'SHA-256'`
* `'SHA-384'`
@@ -1423,6 +1436,53 @@ the message.
The Node.js Web Crypto API implementation only supports zero-length context
which is equivalent to not providing context at all.
### Class: `CShakeParams`
<!-- YAML
added: REPLACEME
-->
#### `cShakeParams.customization`
<!-- YAML
added: REPLACEME
-->
* Type: {ArrayBuffer|TypedArray|DataView|Buffer|undefined}
The `customization` member represents the customization string.
The Node.js Web Crypto API implementation only supports zero-length customization
which is equivalent to not providing customization at all.
#### `cShakeParams.functionName`
<!-- YAML
added: REPLACEME
-->
* Type: {ArrayBuffer|TypedArray|DataView|Buffer|undefined}
The `functionName` member represents represents the function name, used by NIST to define
functions based on cSHAKE.
The Node.js Web Crypto API implementation only supports zero-length functionName
which is equivalent to not providing functionName at all.
#### `cShakeParams.length`
<!-- YAML
added: REPLACEME
-->
* Type: {number} represents the requested output length in bits.
#### `cShakeParams.name`
<!-- YAML
added: REPLACEME
-->
* Type: {string} Must be `'cSHAKE128'`[^modern-algos] or `'cSHAKE256'`[^modern-algos]
### Class: `EcdhKeyDeriveParams`
<!-- YAML
+6 -1
View File
@@ -211,10 +211,15 @@ async function asyncDigest(algorithm, data) {
case 'SHA-384':
// Fall through
case 'SHA-512':
// Fall through
case 'cSHAKE128':
// Fall through
case 'cSHAKE256':
return jobPromise(() => new HashJob(
kCryptoJobAsync,
normalizeHashName(algorithm.name),
data));
data,
algorithm.length));
}
throw lazyDOMException('Unrecognized algorithm name', 'NotSupportedError');
+8
View File
@@ -49,6 +49,14 @@ const kHashNames = {
[kHashContextJwkRsaOaep]: 'RSA-OAEP-512',
[kHashContextJwkHmac]: 'HS512',
},
shake128: {
[kHashContextNode]: 'shake128',
[kHashContextWebCrypto]: 'cSHAKE128',
},
shake256: {
[kHashContextNode]: 'shake256',
[kHashContextWebCrypto]: 'cSHAKE256',
},
};
{
+1 -1
View File
@@ -62,7 +62,7 @@ async function hmacGenerateKey(algorithm, extractable, keyUsages) {
return new InternalCryptoKey(
key,
{ name, length, hash: { name: hash.name } },
{ name, length, hash },
ArrayFrom(usageSet),
extractable);
}
+1 -1
View File
@@ -161,7 +161,7 @@ async function rsaKeyGenerate(
name,
modulusLength,
publicExponent,
hash: { name: hash.name },
hash,
};
let publicUsages;
+6
View File
@@ -285,6 +285,8 @@ const experimentalAlgorithms = ObjectEntries({
importKey: null,
exportKey: null,
},
'cSHAKE128': { digest: 'CShakeParams' },
'cSHAKE256': { digest: 'CShakeParams' },
});
for (const { 0: algorithm, 1: nid } of [
@@ -338,6 +340,10 @@ const simpleAlgorithmDictionaries = {
RsaOaepParams: { label: 'BufferSource' },
RsaHashedImportParams: { hash: 'HashAlgorithmIdentifier' },
EcKeyImportParams: {},
CShakeParams: {
functionName: 'BufferSource',
customization: 'BufferSource',
},
};
function validateMaxBufferLength(data, name) {
+44
View File
@@ -192,6 +192,16 @@ converters.object = (V, opts) => {
const isNonSharedArrayBuffer = isArrayBuffer;
function ensureSHA(V, label) {
if (
typeof V === 'string' ?
!V.toLowerCase().startsWith('sha') :
V.name?.toLowerCase?.().startsWith('sha') === false
)
throw lazyDOMException(
`Only SHA hashes are supported in ${label}`, 'NotSupportedError');
}
converters.Uint8Array = (V, opts = kEmptyObject) => {
if (!ArrayBufferIsView(V) ||
TypedArrayPrototypeGetSymbolToStringTag(V) !== 'Uint8Array') {
@@ -393,6 +403,7 @@ converters.RsaHashedKeyGenParams = createDictionaryConverter(
{
key: 'hash',
converter: converters.HashAlgorithmIdentifier,
validator: (V, dict) => ensureSHA(V, 'RsaHashedKeyGenParams'),
required: true,
},
]);
@@ -403,6 +414,7 @@ converters.RsaHashedImportParams = createDictionaryConverter(
{
key: 'hash',
converter: converters.HashAlgorithmIdentifier,
validator: (V, dict) => ensureSHA(V, 'RsaHashedImportParams'),
required: true,
},
]);
@@ -449,6 +461,7 @@ converters.HmacKeyGenParams = createDictionaryConverter(
{
key: 'hash',
converter: converters.HashAlgorithmIdentifier,
validator: (V, dict) => ensureSHA(V, 'HmacKeyGenParams'),
required: true,
},
{
@@ -503,6 +516,7 @@ converters.EcdsaParams = createDictionaryConverter(
{
key: 'hash',
converter: converters.HashAlgorithmIdentifier,
validator: (V, dict) => ensureSHA(V, 'EcdsaParams'),
required: true,
},
]);
@@ -513,6 +527,7 @@ converters.HmacImportParams = createDictionaryConverter(
{
key: 'hash',
converter: converters.HashAlgorithmIdentifier,
validator: (V, dict) => ensureSHA(V, 'HmacImportParams'),
required: true,
},
{
@@ -573,6 +588,7 @@ converters.HkdfParams = createDictionaryConverter(
{
key: 'hash',
converter: converters.HashAlgorithmIdentifier,
validator: (V, dict) => ensureSHA(V, 'HkdfParams'),
required: true,
},
{
@@ -587,12 +603,40 @@ converters.HkdfParams = createDictionaryConverter(
},
]);
converters.CShakeParams = createDictionaryConverter(
'CShakeParams', [
...new SafeArrayIterator(dictAlgorithm),
{
key: 'length',
converter: (V, opts) =>
converters['unsigned long'](V, { ...opts, enforceRange: true }),
validator: (V, opts) => {
// The Web Crypto spec allows for SHAKE output length that are not multiples of
// 8. We don't.
if (V % 8)
throw lazyDOMException('Unsupported CShakeParams length', 'NotSupportedError');
},
required: true,
},
{
key: 'functionName',
converter: converters.BufferSource,
validator: validateZeroLength('CShakeParams.functionName'),
},
{
key: 'customization',
converter: converters.BufferSource,
validator: validateZeroLength('CShakeParams.customization'),
},
]);
converters.Pbkdf2Params = createDictionaryConverter(
'Pbkdf2Params', [
...new SafeArrayIterator(dictAlgorithm),
{
key: 'hash',
converter: converters.HashAlgorithmIdentifier,
validator: (V, dict) => ensureSHA(V, 'Pbkdf2Params'),
required: true,
},
{
@@ -306,7 +306,6 @@ async function testDeriveBitsBadHash(
hash: 'PBKDF2'
},
baseKeys[size], 256), {
message: /Unrecognized algorithm name/,
name: 'NotSupportedError',
}),
]);
@@ -437,10 +436,7 @@ async function testDeriveKeyBadHash(
keyType,
true,
usages),
{
message: /Unrecognized algorithm name/,
name: 'NotSupportedError',
}),
{ name: 'NotSupportedError' }),
assert.rejects(
subtle.deriveKey(
{
@@ -451,10 +447,7 @@ async function testDeriveKeyBadHash(
keyType,
true,
usages),
{
message: /Unrecognized algorithm name/,
name: 'NotSupportedError',
}),
{ name: 'NotSupportedError' }),
]);
}
+63 -14
View File
@@ -11,10 +11,12 @@ const { subtle } = globalThis.crypto;
const { createHash } = require('crypto');
const kTests = [
['SHA-1', 'sha1', 160],
['SHA-256', 'sha256', 256],
['SHA-384', 'sha384', 384],
['SHA-512', 'sha512', 512],
['SHA-1', ['sha1'], 160],
['SHA-256', ['sha256'], 256],
['SHA-384', ['sha384'], 384],
['SHA-512', ['sha512'], 512],
[{ name: 'cSHAKE128', length: 256 }, ['shake128', { outputLength: 256 >> 3 }], 256],
[{ name: 'cSHAKE256', length: 512 }, ['shake256', { outputLength: 512 >> 3 }], 512],
];
// Empty hash just works, not checking result
@@ -38,12 +40,10 @@ const kData = (new TextEncoder()).encode('hello');
await Promise.all(kTests.map(async (test) => {
// Get the digest using the legacy crypto API
const checkValue =
createHash(test[1]).update(kData).digest().toString('hex');
createHash.apply(createHash, test[1]).update(kData).digest().toString('hex');
// Get the digest using the SubtleCrypto API
const values = Promise.all([
subtle.digest({ name: test[0] }, kData),
subtle.digest({ name: test[0], length: test[2] }, kData),
subtle.digest(test[0], kData),
subtle.digest(test[0], kData.buffer),
subtle.digest(test[0], new DataView(kData.buffer)),
@@ -137,17 +137,53 @@ const kDigestedData = {
long: '4b02caf650276030ea5617e597c5d53fd9daa68b78bfe' +
'60b22aab8d36a4c2a3affdb71234f49276737c575ddf7' +
'4d14054cbd6fdb98fd0ddcbcb46f91ad76b6ee'
}
},
'cshake128': {
empty: '7f9c2ba4e88f827d616045507605853ed73b8093f6e' +
'fbc88eb1a6eacfa66ef26',
short: 'dea62d73e6b59cf725d0320d660089a4475cbbd3b85' +
'39e36691f150d47556794',
medium: 'b1acd53a03e76a221e52ea578e042f686a68c3d1c9' +
'832ab18285cf4f304ca32d',
long: '3a5bf5676955e5dec87d430e526925558971ca14c370' +
'ee5d7cf572b94c7c63d7'
},
'cshake256': {
empty: '46b9dd2b0ba88d13233b3feb743eeb243fcd52ea62b' +
'81b82b50c27646ed5762fd75dc4ddd8c0f200cb0501' +
'9d67b592f6fc821c49479ab48640292eacb3b7c4be',
short: '1738113f5abb3ee5320ee18aa266c3617a7475dbd8e' +
'd9a985994fddd6112ad999ec8e2ebdfeafb96e76f6b' +
'b3a3adba43da60f00cd12496df5af3e28ae6d3de42',
medium: '4146c13d86d9bc186b0b309ab6a124ee0c74ba26b8' +
'c60dcc7b3ed505969aa8d19028c6317999a085b1e6' +
'b6a785ce4ff632aeb27493227e44232fb7b3952141' +
'7b',
long: '0c42bfd1e282622fd8144aa29b072fd09fc2bae70885' +
'd5290933492f9d17411926a613dd0611668c2ac999e8' +
'c011aabaa9004323425fbad75b0f58ee6e777a94'
},
};
async function testDigest(size, name) {
async function testDigest(size, alg) {
const digest = await subtle.digest(
name,
alg,
Buffer.from(kSourceData[size], 'hex'));
assert.strictEqual(
Buffer.from(digest).toString('hex'),
kDigestedData[name.toLowerCase()][size]);
kDigestedData[(alg.name || alg).toLowerCase()][size]);
}
function applyXOF(name) {
if (name.match(/cshake128/i)) {
return { name, length: 256 };
}
if (name.match(/cshake256/i)) {
return { name, length: 512 };
}
return name;
}
(async function() {
@@ -158,9 +194,9 @@ async function testDigest(size, name) {
const downCase = alg.toLowerCase();
const mixedCase = upCase.slice(0, 1) + downCase.slice(1);
variations.push(testDigest(size, upCase));
variations.push(testDigest(size, downCase));
variations.push(testDigest(size, mixedCase));
variations.push(testDigest(size, applyXOF(upCase)));
variations.push(testDigest(size, applyXOF(downCase)));
variations.push(testDigest(size, applyXOF(mixedCase)));
});
});
@@ -172,3 +208,16 @@ async function testDigest(size, name) {
name: 'NotSupportedError',
});
})().then(common.mustCall());
// CShake edge cases
(async () => {
assert.deepStrictEqual(
new Uint8Array(await subtle.digest({ name: 'cSHAKE128', length: 0 }, Buffer.alloc(1))),
new Uint8Array(0),
);
await assert.rejects(subtle.digest({ name: 'cSHAKE128', length: 7 }, Buffer.alloc(1)), {
name: 'NotSupportedError',
message: 'Unsupported CShakeParams length',
});
})().then(common.mustCall());
+2 -9
View File
@@ -177,10 +177,7 @@ if (hasOpenSSL(3, 5)) {
return assert.rejects(
// The extractable and usages values are invalid here also,
// but the unrecognized algorithm name should be caught first.
subtle.generateKey(algorithm, 7, []), {
message: /Unrecognized algorithm name/,
name: 'NotSupportedError',
});
subtle.generateKey(algorithm, 7, []), { name: 'NotSupportedError' });
}
const tests = [
@@ -373,10 +370,7 @@ if (hasOpenSSL(3, 5)) {
modulusLength,
publicExponent,
hash
}, true, usages), {
message: /Unrecognized algorithm name/,
name: 'NotSupportedError',
});
}, true, usages), { name: 'NotSupportedError' });
}));
await Promise.all(['', {}, 1, false].map((usages) => {
@@ -604,7 +598,6 @@ if (hasOpenSSL(3, 5)) {
[1, false, null].forEach(async (hash) => {
await assert.rejects(
subtle.generateKey({ name: 'HMAC', length, hash }, true, usages), {
message: /Unrecognized algorithm name/,
name: 'NotSupportedError',
});
});
@@ -483,7 +483,6 @@ async function testDeriveBitsBadHash(
...algorithm,
hash: hash.substring(0, 3) + hash.substring(4),
}, baseKeys[size], 256), {
message: /Unrecognized algorithm name/,
name: 'NotSupportedError',
}),
assert.rejects(
@@ -493,7 +492,6 @@ async function testDeriveBitsBadHash(
hash: 'HKDF',
},
baseKeys[size], 256), {
message: /Unrecognized algorithm name/,
name: 'NotSupportedError',
}),
]);
@@ -571,10 +569,7 @@ async function testDeriveKeyBadHash(
keyType,
true,
usages),
{
message: /Unrecognized algorithm name/,
name: 'NotSupportedError',
}),
{ name: 'NotSupportedError' }),
assert.rejects(
subtle.deriveKey(
{
@@ -585,10 +580,7 @@ async function testDeriveKeyBadHash(
keyType,
true,
usages),
{
message: /Unrecognized algorithm name/,
name: 'NotSupportedError',
}),
{ name: 'NotSupportedError' }),
]);
}
+1
View File
@@ -121,6 +121,7 @@ const customTypesMap = {
'RsaPssParams': 'webcrypto.html#class-rsapssparams',
'Ed448Params': 'webcrypto.html#class-ed448params',
'ContextParams': 'webcrypto.html#class-contextparams',
'CShakeParams': 'webcrypto.html#class-cshakeparams',
'dgram.Socket': 'dgram.html#class-dgramsocket',