Skip to content

Commit 4c1a277

Browse files
authored
crypto: re-add padding for AES-KW wrapped JWKs
PR-URL: #46563 Reviewed-By: James M Snell <jasnell@gmail.com>
1 parent 96c720e commit 4c1a277

File tree

2 files changed

+17
-8
lines changed

2 files changed

+17
-8
lines changed

lib/internal/crypto/webcrypto.js

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ const {
99
ReflectApply,
1010
ReflectConstruct,
1111
SafeSet,
12+
StringPrototypeRepeat,
1213
SymbolToStringTag,
1314
} = primordials;
1415

@@ -685,7 +686,16 @@ async function wrapKey(format, key, wrappingKey, algorithm) {
685686
let keyData = await ReflectApply(exportKey, this, [format, key]);
686687

687688
if (format === 'jwk') {
688-
keyData = new TextEncoder().encode(JSONStringify(keyData));
689+
const ec = new TextEncoder();
690+
const raw = JSONStringify(keyData);
691+
// As per the NOTE in step 13 https://w3c.github.io/webcrypto/#SubtleCrypto-method-wrapKey
692+
// we're padding AES-KW wrapped JWK to make sure it is always a multiple of 8 bytes
693+
// in length
694+
if (algorithm.name === 'AES-KW' && raw.length % 8 !== 0) {
695+
keyData = ec.encode(raw + StringPrototypeRepeat(' ', 8 - (raw.length % 8)));
696+
} else {
697+
keyData = ec.encode(raw);
698+
}
689699
}
690700

691701
return cipherOrWrap(

test/parallel/test-webcrypto-wrap-unwrap.js

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -231,6 +231,10 @@ function getFormats(key) {
231231
// material length must be a multiple of 8.
232232
// If the wrapping algorithm is RSA-OAEP, the exported key
233233
// material maximum length is a factor of the modulusLength
234+
//
235+
// As per the NOTE in step 13 https://w3c.github.io/webcrypto/#SubtleCrypto-method-wrapKey
236+
// we're padding AES-KW wrapped JWK to make sure it is always a multiple of 8 bytes
237+
// in length
234238
async function wrappingIsPossible(name, exported) {
235239
if ('byteLength' in exported) {
236240
switch (name) {
@@ -239,13 +243,8 @@ async function wrappingIsPossible(name, exported) {
239243
case 'RSA-OAEP':
240244
return exported.byteLength <= 446;
241245
}
242-
} else if ('kty' in exported) {
243-
switch (name) {
244-
case 'AES-KW':
245-
return JSON.stringify(exported).length % 8 === 0;
246-
case 'RSA-OAEP':
247-
return JSON.stringify(exported).length <= 478;
248-
}
246+
} else if ('kty' in exported && name === 'RSA-OAEP') {
247+
return JSON.stringify(exported).length <= 478;
249248
}
250249
return true;
251250
}

0 commit comments

Comments
 (0)