Skip to content

Commit c12ff2c

Browse files
committed
crypto: re-add padding for AES-KW wrapped JWKs
PR-URL: #46563 Reviewed-By: James M Snell <jasnell@gmail.com> Backport-PR-URL: #46252
1 parent 8ebcb1e commit c12ff2c

File tree

2 files changed

+17
-8
lines changed

2 files changed

+17
-8
lines changed

lib/internal/crypto/webcrypto.js

+11-1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ const {
88
ReflectApply,
99
ReflectConstruct,
1010
SafeSet,
11+
StringPrototypeRepeat,
1112
SymbolToStringTag,
1213
} = primordials;
1314

@@ -680,7 +681,16 @@ async function wrapKey(format, key, wrappingKey, algorithm) {
680681
let keyData = await ReflectApply(exportKey, this, [format, key]);
681682

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

686696
return cipherOrWrap(

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

+6-7
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)