Skip to content

Commit 76e4d12

Browse files
panvaRafaelGSS
authored andcommitted
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 9d894c1 commit 76e4d12

2 files changed

Lines changed: 17 additions & 8 deletions

File tree

‎lib/internal/crypto/webcrypto.js‎

Lines changed: 11 additions & 1 deletion
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
letkeyData=awaitReflectApply(exportKey,this,[format,key]);
681682

682683
if(format==='jwk'){
683-
keyData=newTextEncoder().encode(JSONStringify(keyData));
684+
constec=newTextEncoder();
685+
constraw=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
returncipherOrWrap(

‎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
asyncfunctionwrappingIsPossible(name,exported){
235239
if('byteLength'inexported){
236240
switch(name){
@@ -239,13 +243,8 @@ async function wrappingIsPossible(name, exported) {
239243
case'RSA-OAEP':
240244
returnexported.byteLength<=446;
241245
}
242-
}elseif('kty'inexported){
243-
switch(name){
244-
case'AES-KW':
245-
returnJSON.stringify(exported).length%8===0;
246-
case'RSA-OAEP':
247-
returnJSON.stringify(exported).length<=478;
248-
}
246+
}elseif('kty'inexported&&name==='RSA-OAEP'){
247+
returnJSON.stringify(exported).length<=478;
249248
}
250249
returntrue;
251250
}

0 commit comments

Comments
 (0)