Skip to content

Commit

Permalink
fix(ext/node): fix Decipheriv when autoPadding disabled (#25598)
Browse files Browse the repository at this point in the history
This change fixes Decipheriv behavior when autoPadding disabled and enabled.

By this change, the example given in
#20924 (comment)
works in the same way as Node.

closes #20924
  • Loading branch information
kt3k committed Sep 12, 2024
1 parent 0a4a8c7 commit 3f15e30
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
7 changes: 6 additions & 1 deletion ext/node/polyfills/internal/crypto/cipher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,10 @@ class BlockModeCache {
this.cache = this.cache.subarray(len);
return out;
}

set lastChunkIsNonZero(value: boolean) {
this.#lastChunkIsNonZero = value;
}
}

export class Decipheriv extends Transform implements Cipher {
Expand Down Expand Up @@ -338,7 +342,7 @@ export class Decipheriv extends Transform implements Cipher {
},
...options,
});
this.#cache = new BlockModeCache(true);
this.#cache = new BlockModeCache(this.#autoPadding);
this.#context = op_node_create_decipheriv(cipher, toU8(key), toU8(iv));
this.#needsBlockCache =
!(cipher == "aes-128-gcm" || cipher == "aes-256-gcm");
Expand Down Expand Up @@ -386,6 +390,7 @@ export class Decipheriv extends Transform implements Cipher {

setAutoPadding(autoPadding?: boolean): this {
this.#autoPadding = Boolean(autoPadding);
this.#cache.lastChunkIsNonZero = this.#autoPadding;
return this;
}

Expand Down
38 changes: 38 additions & 0 deletions tests/unit_node/crypto/crypto_cipher_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -378,3 +378,41 @@ Deno.test({
assertEquals(info2.ivLength, 16);
},
});

Deno.test({
name:
"createDecipheriv - handling of the last chunk when auto padding enabled/disabled",
fn() {
const algorithm = "aes-256-cbc";
const key = Buffer.from(
"84dcdd964968734fdf0de4a2cba471c2e0a753930b841c014b1e77f456b5797b",
"hex",
);
const val = Buffer.from(
"feabbdf66e2c71cc780d0cd2765dcce283e8ae7e58fcc1a9acafc678581e0e06",
"hex",
);
const iv = Buffer.alloc(16, 0);

{
const decipher = crypto.createDecipheriv(algorithm, key, iv);
decipher.setAutoPadding(false);
assertEquals(
decipher.update(val, undefined, "hex"),
"ed2c908f26571bf8e50d60b77fb9c25f95b933b59111543c6fac41ad6b47e681",
);
assertEquals(decipher.final("hex"), "");
}

{
const decipher = crypto.createDecipheriv(algorithm, key, iv);
assertEquals(
decipher.update(val, undefined, "hex"),
"ed2c908f26571bf8e50d60b77fb9c25f",
);
assertThrows(() => {
decipher.final();
});
}
},
});

0 comments on commit 3f15e30

Please sign in to comment.