Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

crypto: re-add padding for AES-KW wrapped JWKs #46563

Merged
merged 1 commit into from
Feb 17, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 11 additions & 1 deletion lib/internal/crypto/webcrypto.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const {
ReflectApply,
ReflectConstruct,
SafeSet,
StringPrototypeRepeat,
SymbolToStringTag,
} = primordials;

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

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

return cipherOrWrap(
Expand Down
13 changes: 6 additions & 7 deletions test/parallel/test-webcrypto-wrap-unwrap.js
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,10 @@ function getFormats(key) {
// material length must be a multiple of 8.
// If the wrapping algorithm is RSA-OAEP, the exported key
// material maximum length is a factor of the modulusLength
//
// As per the NOTE in step 13 https://w3c.github.io/webcrypto/#SubtleCrypto-method-wrapKey
// we're padding AES-KW wrapped JWK to make sure it is always a multiple of 8 bytes
// in length
async function wrappingIsPossible(name, exported) {
if ('byteLength' in exported) {
switch (name) {
Expand All @@ -239,13 +243,8 @@ async function wrappingIsPossible(name, exported) {
case 'RSA-OAEP':
return exported.byteLength <= 446;
}
} else if ('kty' in exported) {
switch (name) {
case 'AES-KW':
return JSON.stringify(exported).length % 8 === 0;
case 'RSA-OAEP':
return JSON.stringify(exported).length <= 478;
}
} else if ('kty' in exported && name === 'RSA-OAEP') {
return JSON.stringify(exported).length <= 478;
}
return true;
}
Expand Down