Skip to content

Commit 9416371

Browse files
committed
crypto: add SubtleCrypto.supports feature detection in Web Crypto API
1 parent 040fa05 commit 9416371

File tree

6 files changed

+440
-0
lines changed

6 files changed

+440
-0
lines changed

doc/api/webcrypto.md

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -351,6 +351,74 @@ async function digest(data, algorithm = 'SHA-512') {
351351
}
352352
```
353353

354+
### Checking for runtime algorithm support
355+
356+
> Stability: 1.0 - Early development. SubleCrypto.supports is an experimental
357+
> implementation based on [Modern Algorithms in the Web Cryptography API][] as
358+
> of 8 January 2025
359+
360+
This example derives a key from a password using Argon2, if available,
361+
or PBKDF2, otherwise; and then encrypts and decrypts some text with it
362+
using AES-OCB, if available, and AES-GCM, otherwise.
363+
364+
```mjs
365+
const password = 'correct horse battery staple';
366+
const derivationAlg =
367+
SubtleCrypto.supports?.('importKey', 'Argon2id') ?
368+
'Argon2id' :
369+
'PBKDF2';
370+
const encryptionAlg =
371+
SubtleCrypto.supports?.('importKey', 'AES-OCB') ?
372+
'AES-OCB' :
373+
'AES-GCM';
374+
const passwordKey = await crypto.subtle.importKey(
375+
'raw',
376+
new TextEncoder().encode(password),
377+
derivationAlg,
378+
false,
379+
['deriveKey'],
380+
);
381+
const nonce = crypto.getRandomValues(new Uint8Array(16));
382+
const derivationParams =
383+
derivationAlg === 'Argon2id' ?
384+
{
385+
nonce,
386+
parallelism: 4,
387+
memory: 2 ** 21,
388+
passes: 1,
389+
} :
390+
{
391+
salt: nonce,
392+
iterations: 100_000,
393+
hash: 'SHA-256',
394+
};
395+
const key = await crypto.subtle.deriveKey(
396+
{
397+
name: derivationAlg,
398+
...derivationParams,
399+
},
400+
passwordKey,
401+
{
402+
name: encryptionAlg,
403+
length: 256,
404+
},
405+
false,
406+
['encrypt', 'decrypt'],
407+
);
408+
const plaintext = 'Hello, world!';
409+
const iv = crypto.getRandomValues(new Uint8Array(16));
410+
const encrypted = await crypto.subtle.encrypt(
411+
{ name: encryptionAlg, iv },
412+
key,
413+
new TextEncoder().encode(plaintext),
414+
);
415+
const decrypted = new TextDecoder().decode(await crypto.subtle.decrypt(
416+
{ name: encryptionAlg, iv },
417+
key,
418+
encrypted,
419+
));
420+
```
421+
354422
## Algorithm matrix
355423
356424
The table details the algorithms supported by the Node.js Web Crypto API
@@ -549,6 +617,28 @@ added: v15.0.0
549617
added: v15.0.0
550618
-->
551619
620+
### Static method: `SubtleCrypto.supports(operation, algorithm[, lengthOrAdditionalAlgorithm])`
621+
622+
> Stability: 1.0 - Early development. An experimental implementation of SubtleCrypto.supports from
623+
> [Modern Algorithms in the Web Cryptography API][] as of 8 January 2025
624+
625+
<!-- YAML
626+
added: REPLACEME
627+
-->
628+
629+
<!--lint disable maximum-line-length remark-lint-->
630+
631+
* `operation`: {string} "encrypt", "decrypt", "sign", "verify", "digest", "generateKey", "deriveKey", "deriveBits", "importKey", "exportKey", "wrapKey" or "unwrapKey"
632+
* `algorithm`: {AesCbcParams|AesCtrParams|AesGcmParams|AesKeyGenParams|AlgorithmIdentifier|EcdhKeyDeriveParams|EcdsaParams|EcKeyGenParams|EcKeyImportParams|Ed448Params|HkdfParams|HmacImportParams|HmacKeyGenParams|Pbkdf2Params|RsaHashedImportParams|RsaHashedKeyGenParams|RsaOaepParams|RsaPssParams|string}
633+
* `lengthOrAdditionalAlgorithm`: Depending on the operation this is either ignored, the value of the SubtleCrypto method's length argument, the algorithm of key to be derived when operation is "deriveKey", the algorithm of key to be exported before wrapping when operation is "wrapKey", and the algorithm of key to be imported after unwrapping when operation is "unwrapKey"
634+
* Returns: {boolean} Indicating whether the implementation supports the given operation
635+
636+
<!--lint enable maximum-line-length remark-lint-->
637+
638+
Allows feature detection in Web Crypto API, which can be used to detect whether
639+
a given algorithm identifier (including any of its parameters) is supported for
640+
the given operation.
641+
552642
### `subtle.decrypt(algorithm, key, data)`
553643
554644
<!-- YAML
@@ -1653,6 +1743,7 @@ The length (in bytes) of the random salt to use.
16531743
16541744
[JSON Web Key]: https://tools.ietf.org/html/rfc7517
16551745
[Key usages]: #cryptokeyusages
1746+
[Modern Algorithms in the Web Cryptography API]: https://twiss.github.io/webcrypto-modern-algos/
16561747
[NIST SP 800-38D]: https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf
16571748
[RFC 4122]: https://www.rfc-editor.org/rfc/rfc4122.txt
16581749
[Secure Curves in the Web Cryptography API]: https://wicg.github.io/webcrypto-secure-curves/

lib/internal/crypto/hkdf.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,4 +170,5 @@ module.exports = {
170170
hkdf,
171171
hkdfSync,
172172
hkdfDeriveBits,
173+
validateHkdfDeriveBitsLength,
173174
};

lib/internal/crypto/pbkdf2.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,4 +128,5 @@ module.exports = {
128128
pbkdf2,
129129
pbkdf2Sync,
130130
pbkdf2DeriveBits,
131+
validatePbkdf2DeriveBitsLength,
131132
};

lib/internal/crypto/util.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,20 @@ const kSupportedAlgorithms = {
175175
'SHA-384': null,
176176
'SHA-512': null,
177177
},
178+
'exportKey': {
179+
'RSASSA-PKCS1-v1_5': null,
180+
'RSA-PSS': null,
181+
'RSA-OAEP': null,
182+
'ECDSA': null,
183+
'ECDH': null,
184+
'HMAC': null,
185+
'AES-CTR': null,
186+
'AES-CBC': null,
187+
'AES-GCM': null,
188+
'AES-KW': null,
189+
'Ed25519': null,
190+
'X25519': null,
191+
},
178192
'generateKey': {
179193
'RSASSA-PKCS1-v1_5': 'RsaHashedKeyGenParams',
180194
'RSA-PSS': 'RsaHashedKeyGenParams',
@@ -259,12 +273,14 @@ const experimentalAlgorithms = ObjectEntries({
259273
generateKey: null,
260274
importKey: null,
261275
deriveBits: 'EcdhKeyDeriveParams',
276+
exportKey: null,
262277
},
263278
'Ed448': {
264279
generateKey: null,
265280
sign: 'Ed448Params',
266281
verify: 'Ed448Params',
267282
importKey: null,
283+
exportKey: null,
268284
},
269285
});
270286

lib/internal/crypto/webcrypto.js

Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ const {
4747
} = require('internal/crypto/util');
4848

4949
const {
50+
emitExperimentalWarning,
5051
kEnumerableProperty,
5152
lazyDOMException,
5253
} = require('internal/util');
@@ -922,7 +923,149 @@ class SubtleCrypto {
922923
constructor() {
923924
throw new ERR_ILLEGAL_CONSTRUCTOR();
924925
}
926+
927+
static supports(operation, algorithm, lengthOrAdditionalAlgorithm = null) {
928+
emitExperimentalWarning('The supports Web Crypto API method');
929+
if (this !== SubtleCrypto) throw new ERR_INVALID_THIS('SubtleCrypto constructor');
930+
webidl ??= require('internal/crypto/webidl');
931+
const prefix = "Failed to execute 'supports' on 'SubtleCrypto'";
932+
webidl.requiredArguments(arguments.length, 2, { prefix });
933+
934+
operation = webidl.converters.DOMString(operation, {
935+
prefix,
936+
context: '1st argument',
937+
});
938+
algorithm = webidl.converters.AlgorithmIdentifier(algorithm, {
939+
prefix,
940+
context: '2nd argument',
941+
});
942+
943+
switch (operation) {
944+
case 'encrypt':
945+
case 'decrypt':
946+
case 'sign':
947+
case 'verify':
948+
case 'digest':
949+
case 'generateKey':
950+
case 'deriveKey':
951+
case 'deriveBits':
952+
case 'importKey':
953+
case 'exportKey':
954+
case 'wrapKey':
955+
case 'unwrapKey':
956+
break;
957+
default:
958+
return false;
959+
}
960+
961+
let length;
962+
let additionalAlgorithm;
963+
if (operation === 'deriveKey') {
964+
additionalAlgorithm = webidl.converters.AlgorithmIdentifier(lengthOrAdditionalAlgorithm, {
965+
prefix,
966+
context: '3rd argument',
967+
});
968+
969+
if (!check('importKey', additionalAlgorithm) || !check('get key length', additionalAlgorithm)) {
970+
return false;
971+
}
972+
}
973+
974+
if (operation === 'wrapKey') {
975+
additionalAlgorithm = webidl.converters.AlgorithmIdentifier(lengthOrAdditionalAlgorithm, {
976+
prefix,
977+
context: '3rd argument',
978+
});
979+
980+
if (!check('exportKey', additionalAlgorithm)) {
981+
return false;
982+
}
983+
}
984+
985+
if (operation === 'unwrapKey') {
986+
additionalAlgorithm = webidl.converters.AlgorithmIdentifier(lengthOrAdditionalAlgorithm, {
987+
prefix,
988+
context: '3rd argument',
989+
});
990+
991+
if (!check('importKey', additionalAlgorithm)) {
992+
return false;
993+
}
994+
}
995+
996+
if (operation === 'deriveBits') {
997+
length = lengthOrAdditionalAlgorithm;
998+
if (length !== null) {
999+
length = webidl.converters['unsigned long'](length, {
1000+
prefix,
1001+
context: '3rd argument',
1002+
});
1003+
}
1004+
}
1005+
1006+
return check(operation, algorithm, length);
1007+
}
1008+
}
1009+
1010+
function check(op, alg, length) {
1011+
if (op === 'deriveKey') {
1012+
op = 'deriveBits';
1013+
}
1014+
1015+
let normalizedAlgorithm;
1016+
try {
1017+
normalizedAlgorithm = normalizeAlgorithm(alg, op);
1018+
} catch {
1019+
if (op === 'wrapKey') {
1020+
return check('encrypt', alg);
1021+
}
1022+
1023+
if (op === 'unwrapKey') {
1024+
return check('decrypt', alg);
1025+
}
1026+
1027+
return false;
1028+
}
1029+
1030+
switch (op) {
1031+
case 'encrypt':
1032+
case 'get key length':
1033+
case 'decrypt':
1034+
case 'sign':
1035+
case 'verify':
1036+
case 'digest':
1037+
case 'generateKey':
1038+
case 'importKey':
1039+
case 'exportKey':
1040+
case 'wrapKey':
1041+
case 'unwrapKey':
1042+
return true;
1043+
case 'deriveBits': {
1044+
if (normalizedAlgorithm.name === 'HKDF') {
1045+
try {
1046+
require('internal/crypto/hkdf').validateHkdfDeriveBitsLength(length);
1047+
} catch {
1048+
return false;
1049+
}
1050+
}
1051+
1052+
if (normalizedAlgorithm.name === 'PBKDF2') {
1053+
try {
1054+
require('internal/crypto/pbkdf2').validatePbkdf2DeriveBitsLength(length);
1055+
} catch {
1056+
return false;
1057+
}
1058+
}
1059+
1060+
return true;
1061+
}
1062+
default: {
1063+
const assert = require('internal/assert');
1064+
assert.fail('Unreachable code');
1065+
}
1066+
}
9251067
}
1068+
9261069
const subtle = ReflectConstruct(function() {}, [], SubtleCrypto);
9271070

9281071
class Crypto {

0 commit comments

Comments
 (0)