Skip to content

Commit a848faf

Browse files
committed
crypto: add SubtleCrypto.supports feature detection in Web Crypto API
1 parent dac91a9 commit a848faf

File tree

7 files changed

+558
-0
lines changed

7 files changed

+558
-0
lines changed

doc/api/webcrypto.md

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

355+
### Checking for runtime algorithm support
356+
357+
> Stability: 1.0 - Early development. SubleCrypto.supports is an experimental
358+
> implementation based on [Modern Algorithms in the Web Cryptography API][]
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+
355422
## Algorithm matrix
356423
357424
The table details the algorithms supported by the Node.js Web Crypto API
@@ -550,6 +617,28 @@ added: v15.0.0
550617
added: v15.0.0
551618
-->
552619
620+
### Static method: `SubtleCrypto.supports(operation, algorithm[, lengthOrAdditionalAlgorithm])`
621+
622+
> Stability: 1.0 - Early development. SubleCrypto.supports is an experimental
623+
> implementation based on [Modern Algorithms in the Web Cryptography API][]
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` {string|Algorithm|AesCbcParams|AesCtrParams|AesGcmParams|AesKeyGenParams|EcdhKeyDeriveParams|EcdsaParams|EcKeyGenParams|EcKeyImportParams|Ed448Params|HkdfParams|HmacImportParams|HmacKeyGenParams|Pbkdf2Params|RsaHashedImportParams|RsaHashedKeyGenParams|RsaOaepParams|RsaPssParams}
633+
* `lengthOrAdditionalAlgorithm` {null|number|string|Algorithm|AesCbcParams|AesCtrParams|AesDerivedKeyParams|AesGcmParams|AesKeyGenParams|EcdhKeyDeriveParams|EcdsaParams|EcKeyGenParams|EcKeyImportParams|Ed448Params|HkdfParams|HmacImportParams|HmacKeyGenParams|Pbkdf2Params|RsaHashedImportParams|RsaHashedKeyGenParams|RsaOaepParams|RsaPssParams} Depending on the operation this is either ignored, the value of the length argument when operation is "deriveBits", the algorithm of key to be derived when operation is "deriveKey", the algorithm of key to be exported before wrapping when operation is "wrapKey", or the algorithm of key to be imported after unwrapping when operation is "unwrapKey". **Default:** `null` when operation is "deriveBits", `undefined` otherwise.
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+
553642
### `subtle.decrypt(algorithm, key, data)`
554643
555644
<!-- YAML
@@ -1808,6 +1897,7 @@ The length (in bytes) of the random salt to use.
18081897
18091898
[JSON Web Key]: https://tools.ietf.org/html/rfc7517
18101899
[Key usages]: #cryptokeyusages
1900+
[Modern Algorithms in the Web Cryptography API]: https://wicg.github.io/webcrypto-modern-algos/
18111901
[NIST SP 800-38D]: https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf
18121902
[RFC 4122]: https://www.rfc-editor.org/rfc/rfc4122.txt
18131903
[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/webcrypto.js

Lines changed: 147 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');
@@ -939,7 +940,153 @@ class SubtleCrypto {
939940
constructor() {
940941
throw new ERR_ILLEGAL_CONSTRUCTOR();
941942
}
943+
944+
static supports(operation, algorithm, lengthOrAdditionalAlgorithm = null) {
945+
emitExperimentalWarning('The supports Web Crypto API method');
946+
if (this !== SubtleCrypto) throw new ERR_INVALID_THIS('SubtleCrypto constructor');
947+
webidl ??= require('internal/crypto/webidl');
948+
const prefix = "Failed to execute 'supports' on 'SubtleCrypto'";
949+
webidl.requiredArguments(arguments.length, 2, { prefix });
950+
951+
operation = webidl.converters.DOMString(operation, {
952+
prefix,
953+
context: '1st argument',
954+
});
955+
algorithm = webidl.converters.AlgorithmIdentifier(algorithm, {
956+
prefix,
957+
context: '2nd argument',
958+
});
959+
960+
switch (operation) {
961+
case 'encrypt':
962+
case 'decrypt':
963+
case 'sign':
964+
case 'verify':
965+
case 'digest':
966+
case 'generateKey':
967+
case 'deriveKey':
968+
case 'deriveBits':
969+
case 'importKey':
970+
case 'exportKey':
971+
case 'wrapKey':
972+
case 'unwrapKey':
973+
break;
974+
default:
975+
return false;
976+
}
977+
978+
let length;
979+
let additionalAlgorithm;
980+
if (operation === 'deriveKey') {
981+
additionalAlgorithm = webidl.converters.AlgorithmIdentifier(lengthOrAdditionalAlgorithm, {
982+
prefix,
983+
context: '3rd argument',
984+
});
985+
986+
if (!check('importKey', additionalAlgorithm)) {
987+
return false;
988+
}
989+
990+
try {
991+
length = getKeyLength(normalizeAlgorithm(additionalAlgorithm, 'get key length'));
992+
} catch {
993+
return false;
994+
}
995+
996+
operation = 'deriveBits';
997+
} else if (operation === 'wrapKey') {
998+
additionalAlgorithm = webidl.converters.AlgorithmIdentifier(lengthOrAdditionalAlgorithm, {
999+
prefix,
1000+
context: '3rd argument',
1001+
});
1002+
1003+
if (!check('exportKey', additionalAlgorithm)) {
1004+
return false;
1005+
}
1006+
} else if (operation === 'unwrapKey') {
1007+
additionalAlgorithm = webidl.converters.AlgorithmIdentifier(lengthOrAdditionalAlgorithm, {
1008+
prefix,
1009+
context: '3rd argument',
1010+
});
1011+
1012+
if (!check('importKey', additionalAlgorithm)) {
1013+
return false;
1014+
}
1015+
} else if (operation === 'deriveBits') {
1016+
length = lengthOrAdditionalAlgorithm;
1017+
if (length !== null) {
1018+
length = webidl.converters['unsigned long'](length, {
1019+
prefix,
1020+
context: '3rd argument',
1021+
});
1022+
}
1023+
}
1024+
1025+
return check(operation, algorithm, length);
1026+
}
1027+
}
1028+
1029+
function check(op, alg, length) {
1030+
let normalizedAlgorithm;
1031+
try {
1032+
normalizedAlgorithm = normalizeAlgorithm(alg, op);
1033+
} catch {
1034+
if (op === 'wrapKey') {
1035+
return check('encrypt', alg);
1036+
}
1037+
1038+
if (op === 'unwrapKey') {
1039+
return check('decrypt', alg);
1040+
}
1041+
1042+
return false;
1043+
}
1044+
1045+
switch (op) {
1046+
case 'encrypt':
1047+
case 'decrypt':
1048+
case 'sign':
1049+
case 'verify':
1050+
case 'digest':
1051+
case 'generateKey':
1052+
case 'importKey':
1053+
case 'exportKey':
1054+
case 'wrapKey':
1055+
case 'unwrapKey':
1056+
return true;
1057+
case 'deriveBits': {
1058+
if (normalizedAlgorithm.name === 'HKDF') {
1059+
try {
1060+
require('internal/crypto/hkdf').validateHkdfDeriveBitsLength(length);
1061+
} catch {
1062+
return false;
1063+
}
1064+
}
1065+
1066+
if (normalizedAlgorithm.name === 'PBKDF2') {
1067+
try {
1068+
require('internal/crypto/pbkdf2').validatePbkdf2DeriveBitsLength(length);
1069+
} catch {
1070+
return false;
1071+
}
1072+
}
1073+
1074+
return true;
1075+
}
1076+
case 'get key length':
1077+
try {
1078+
getKeyLength(alg);
1079+
return true;
1080+
} catch {
1081+
return false;
1082+
}
1083+
default: {
1084+
const assert = require('internal/assert');
1085+
assert.fail('Unreachable code');
1086+
}
1087+
}
9421088
}
1089+
9431090
const subtle = ReflectConstruct(function() {}, [], SubtleCrypto);
9441091

9451092
class Crypto {

0 commit comments

Comments
 (0)