diff --git a/ext/node/ops/crypto/cipher.rs b/ext/node/ops/crypto/cipher.rs index 1072cc8c0fb1e1..7cc7914ed92adc 100644 --- a/ext/node/ops/crypto/cipher.rs +++ b/ext/node/ops/crypto/cipher.rs @@ -67,11 +67,12 @@ impl CipherContext { self, input: &[u8], output: &mut [u8], + auto_padding: bool, ) -> Result { Rc::try_unwrap(self.cipher) .map_err(|_| type_error("Cipher context is already in use"))? .into_inner() - .r#final(input, output) + .r#final(input, output, auto_padding) } } @@ -95,11 +96,12 @@ impl DecipherContext { input: &[u8], output: &mut [u8], auth_tag: &[u8], + auto_padding: bool, ) -> Result<(), AnyError> { Rc::try_unwrap(self.decipher) .map_err(|_| type_error("Decipher context is already in use"))? .into_inner() - .r#final(input, output, auth_tag) + .r#final(input, output, auth_tag, auto_padding) } } @@ -209,40 +211,96 @@ impl Cipher { } /// r#final encrypts the last block of the input data. - fn r#final(self, input: &[u8], output: &mut [u8]) -> Result { + fn r#final( + self, + input: &[u8], + output: &mut [u8], + auto_padding: bool, + ) -> Result { assert!(input.len() < 16); use Cipher::*; match self { - Aes128Cbc(encryptor) => { - let _ = (*encryptor) - .encrypt_padded_b2b_mut::(input, output) - .map_err(|_| type_error("Cannot pad the input data"))?; + Aes128Cbc(mut encryptor) => { + if auto_padding { + let _ = (*encryptor) + .encrypt_padded_b2b_mut::(input, output) + .map_err(|_| type_error("Cannot pad the input data"))?; + } else { + assert!(input.len() % 16 == 0); + for (input, output) in input.chunks(16).zip(output.chunks_mut(16)) { + encryptor.encrypt_block_b2b_mut(input.into(), output.into()); + } + } Ok(None) } - Aes128Ecb(encryptor) => { - let _ = (*encryptor) - .encrypt_padded_b2b_mut::(input, output) - .map_err(|_| type_error("Cannot pad the input data"))?; + Aes128Ecb(mut encryptor) => { + if auto_padding { + let _ = (*encryptor) + .encrypt_padded_b2b_mut::(input, output) + .map_err(|_| type_error("Cannot pad the input data"))?; + } else { + assert!(input.len() % 16 == 0); + for (input, output) in input.chunks(16).zip(output.chunks_mut(16)) { + encryptor.encrypt_block_b2b_mut(input.into(), output.into()); + } + } Ok(None) } - Aes192Ecb(encryptor) => { - let _ = (*encryptor) - .encrypt_padded_b2b_mut::(input, output) - .map_err(|_| type_error("Cannot pad the input data"))?; + Aes192Ecb(mut encryptor) => { + if auto_padding { + let _ = (*encryptor) + .encrypt_padded_b2b_mut::(input, output) + .map_err(|_| type_error("Cannot pad the input data"))?; + } else { + assert!(input.len() % 16 == 0); + for (input, output) in input.chunks(16).zip(output.chunks_mut(16)) { + encryptor.encrypt_block_b2b_mut(input.into(), output.into()); + } + } Ok(None) } - Aes256Ecb(encryptor) => { - let _ = (*encryptor) - .encrypt_padded_b2b_mut::(input, output) - .map_err(|_| type_error("Cannot pad the input data"))?; + Aes256Ecb(mut encryptor) => { + if auto_padding { + let _ = (*encryptor) + .encrypt_padded_b2b_mut::(input, output) + .map_err(|_| type_error("Cannot pad the input data"))?; + } else { + assert!(input.len() % 16 == 0); + for (input, output) in input.chunks(16).zip(output.chunks_mut(16)) { + encryptor.encrypt_block_b2b_mut(input.into(), output.into()); + } + } Ok(None) } - Aes128Gcm(cipher) => Ok(Some(cipher.finish().to_vec())), - Aes256Gcm(cipher) => Ok(Some(cipher.finish().to_vec())), - Aes256Cbc(encryptor) => { - let _ = (*encryptor) - .encrypt_padded_b2b_mut::(input, output) - .map_err(|_| type_error("Cannot pad the input data"))?; + Aes128Gcm(mut cipher) => { + if auto_padding { + Ok(Some(cipher.finish().to_vec())) + } else { + output[..input.len()].copy_from_slice(input); + cipher.encrypt(output); + Ok(None) + } + } + Aes256Gcm(mut cipher) => { + if auto_padding { + Ok(Some(cipher.finish().to_vec())) + } else { + output[..input.len()].copy_from_slice(input); + cipher.encrypt(output); + Ok(None) + } + } + Aes256Cbc(mut encryptor) => { + if auto_padding { + let _ = (*encryptor) + .encrypt_padded_b2b_mut::(input, output) + .map_err(|_| type_error("Cannot pad the input data"))?; + } else { + assert!(input.len() % 16 == 0); + for (input, output) in input.chunks(16).zip(output.chunks_mut(16)) { + encryptor.encrypt_block_b2b_mut(input.into(), output.into()); + } + } Ok(None) } } @@ -348,58 +406,102 @@ impl Decipher { input: &[u8], output: &mut [u8], auth_tag: &[u8], + auto_padding: bool, ) -> Result<(), AnyError> { use Decipher::*; match self { - Aes128Cbc(decryptor) => { - assert!(input.len() == 16); - let _ = (*decryptor) - .decrypt_padded_b2b_mut::(input, output) - .map_err(|_| type_error("Cannot unpad the input data"))?; + Aes128Cbc(mut decryptor) => { + assert!(input.len() % 16 == 0); + if auto_padding { + let _ = (*decryptor) + .decrypt_padded_b2b_mut::(input, output) + .map_err(|_| type_error("Cannot unpad the input data"))?; + } else { + for (input, output) in input.chunks(16).zip(output.chunks_mut(16)) { + decryptor.decrypt_block_b2b_mut(input.into(), output.into()); + } + } Ok(()) } - Aes128Ecb(decryptor) => { - assert!(input.len() == 16); - let _ = (*decryptor) - .decrypt_padded_b2b_mut::(input, output) - .map_err(|_| type_error("Cannot unpad the input data"))?; + Aes128Ecb(mut decryptor) => { + assert!(input.len() % 16 == 0); + if auto_padding { + let _ = (*decryptor) + .decrypt_padded_b2b_mut::(input, output) + .map_err(|_| type_error("Cannot unpad the input data"))?; + } else { + for (input, output) in input.chunks(16).zip(output.chunks_mut(16)) { + decryptor.decrypt_block_b2b_mut(input.into(), output.into()); + } + } Ok(()) } - Aes192Ecb(decryptor) => { - assert!(input.len() == 16); - let _ = (*decryptor) - .decrypt_padded_b2b_mut::(input, output) - .map_err(|_| type_error("Cannot unpad the input data"))?; + Aes192Ecb(mut decryptor) => { + assert!(input.len() % 16 == 0); + if auto_padding { + let _ = (*decryptor) + .decrypt_padded_b2b_mut::(input, output) + .map_err(|_| type_error("Cannot unpad the input data"))?; + } else { + for (input, output) in input.chunks(16).zip(output.chunks_mut(16)) { + decryptor.decrypt_block_b2b_mut(input.into(), output.into()); + } + } Ok(()) } - Aes256Ecb(decryptor) => { - assert!(input.len() == 16); - let _ = (*decryptor) - .decrypt_padded_b2b_mut::(input, output) - .map_err(|_| type_error("Cannot unpad the input data"))?; + Aes256Ecb(mut decryptor) => { + assert!(input.len() % 16 == 0); + if auto_padding { + let _ = (*decryptor) + .decrypt_padded_b2b_mut::(input, output) + .map_err(|_| type_error("Cannot unpad the input data"))?; + } else { + for (input, output) in input.chunks(16).zip(output.chunks_mut(16)) { + decryptor.decrypt_block_b2b_mut(input.into(), output.into()); + } + } + Ok(()) } - Aes128Gcm(decipher) => { - let tag = decipher.finish(); - if tag.as_slice() == auth_tag { - Ok(()) + Aes128Gcm(mut decipher) => { + if auto_padding { + let tag = decipher.finish(); + if tag.as_slice() == auth_tag { + Ok(()) + } else { + Err(type_error("Failed to authenticate data")) + } } else { - Err(type_error("Failed to authenticate data")) + output[..input.len()].copy_from_slice(input); + decipher.decrypt(output); + Ok(()) } } - Aes256Gcm(decipher) => { - let tag = decipher.finish(); - if tag.as_slice() == auth_tag { - Ok(()) + Aes256Gcm(mut decipher) => { + if auto_padding { + let tag = decipher.finish(); + if tag.as_slice() == auth_tag { + Ok(()) + } else { + Err(type_error("Failed to authenticate data")) + } } else { - Err(type_error("Failed to authenticate data")) + output[..input.len()].copy_from_slice(input); + decipher.decrypt(output); + Ok(()) } } - Aes256Cbc(decryptor) => { - assert!(input.len() == 16); - let _ = (*decryptor) - .decrypt_padded_b2b_mut::(input, output) - .map_err(|_| type_error("Cannot unpad the input data"))?; + Aes256Cbc(mut decryptor) => { + assert!(input.len() % 16 == 0); + if auto_padding { + let _ = (*decryptor) + .decrypt_padded_b2b_mut::(input, output) + .map_err(|_| type_error("Cannot unpad the input data"))?; + } else { + for (input, output) in input.chunks(16).zip(output.chunks_mut(16)) { + decryptor.decrypt_block_b2b_mut(input.into(), output.into()); + } + } Ok(()) } } diff --git a/ext/node/ops/crypto/mod.rs b/ext/node/ops/crypto/mod.rs index f73d96580a1e21..e2301dd48d1e53 100644 --- a/ext/node/ops/crypto/mod.rs +++ b/ext/node/ops/crypto/mod.rs @@ -292,11 +292,12 @@ pub fn op_node_cipheriv_final( #[smi] rid: u32, #[buffer] input: &[u8], #[buffer] output: &mut [u8], + auto_padding: bool, ) -> Result>, AnyError> { let context = state.resource_table.take::(rid)?; let context = Rc::try_unwrap(context) .map_err(|_| type_error("Cipher context is already in use"))?; - context.r#final(input, output) + context.r#final(input, output, auto_padding) } #[op2(fast)] @@ -351,11 +352,12 @@ pub fn op_node_decipheriv_final( #[buffer] input: &[u8], #[buffer] output: &mut [u8], #[buffer] auth_tag: &[u8], + auto_padding: bool, ) -> Result<(), AnyError> { let context = state.resource_table.take::(rid)?; let context = Rc::try_unwrap(context) .map_err(|_| type_error("Cipher context is already in use"))?; - context.r#final(input, output, auth_tag) + context.r#final(input, output, auth_tag, auto_padding) } #[op2] diff --git a/ext/node/polyfills/internal/crypto/cipher.ts b/ext/node/polyfills/internal/crypto/cipher.ts index 20971a8c7ce715..3ba8cf8ea3df24 100644 --- a/ext/node/polyfills/internal/crypto/cipher.ts +++ b/ext/node/polyfills/internal/crypto/cipher.ts @@ -151,7 +151,8 @@ export interface DecipherOCB extends Decipher { ): this; } -function toU8(input: string | Uint8Array): Uint8Array { +function toU8(input: string | Uint8Array | null): Uint8Array { + if (input === null) return new Uint8Array(0); return typeof input === "string" ? encode(input) : input; } @@ -166,6 +167,8 @@ export class Cipheriv extends Transform implements Cipher { #authTag?: Buffer; + #autoPadding: boolean; + constructor( cipher: string, key: CipherKey, @@ -190,6 +193,7 @@ export class Cipheriv extends Transform implements Cipher { if (this.#context == 0) { throw new TypeError("Unknown cipher"); } + this.#autoPadding = true; } final(encoding: string = getDefaultEncoding()): Buffer | string { @@ -198,6 +202,7 @@ export class Cipheriv extends Transform implements Cipher { this.#context, this.#cache.cache, buf, + this.#autoPadding, ); if (maybeTag) { this.#authTag = Buffer.from(maybeTag); @@ -220,8 +225,8 @@ export class Cipheriv extends Transform implements Cipher { return this; } - setAutoPadding(_autoPadding?: boolean): this { - notImplemented("crypto.Cipheriv.prototype.setAutoPadding"); + setAutoPadding(autoPadding: boolean): this { + this.#autoPadding = !!autoPadding; return this; } @@ -309,6 +314,8 @@ export class Decipheriv extends Transform implements Cipher { #authTag?: BinaryLike; + #autoPadding: boolean; + constructor( cipher: string, key: CipherKey, @@ -333,6 +340,7 @@ export class Decipheriv extends Transform implements Cipher { if (this.#context == 0) { throw new TypeError("Unknown cipher"); } + this.#autoPadding = true; } final(encoding: string = getDefaultEncoding()): Buffer | string { @@ -342,6 +350,7 @@ export class Decipheriv extends Transform implements Cipher { this.#cache.cache, buf, this.#authTag || NO_TAG, + this.#autoPadding, ); if (!this.#needsBlockCache) { @@ -367,8 +376,9 @@ export class Decipheriv extends Transform implements Cipher { return this; } - setAutoPadding(_autoPadding?: boolean): this { - notImplemented("crypto.Decipheriv.prototype.setAutoPadding"); + setAutoPadding(autoPadding: boolean): this { + this.#autoPadding = !!autoPadding; + return this; } update( diff --git a/tests/node_compat/config.jsonc b/tests/node_compat/config.jsonc index d84cc4dd2c3f8e..21b80b9969acdc 100644 --- a/tests/node_compat/config.jsonc +++ b/tests/node_compat/config.jsonc @@ -248,6 +248,7 @@ "test-crypto-dh.js", "test-crypto-hkdf.js", "test-crypto-hmac.js", + "test-crypto-padding-aes256.js", "test-crypto-prime.js", "test-crypto-secret-keygen.js", "test-crypto-stream.js", diff --git a/tests/node_compat/test/parallel/test-crypto-padding-aes256.js b/tests/node_compat/test/parallel/test-crypto-padding-aes256.js new file mode 100644 index 00000000000000..710942cdd6e91d --- /dev/null +++ b/tests/node_compat/test/parallel/test-crypto-padding-aes256.js @@ -0,0 +1,67 @@ +// deno-fmt-ignore-file +// deno-lint-ignore-file + +// Copyright Joyent and Node contributors. All rights reserved. MIT license. +// Taken from Node 18.12.1 +// This file is automatically generated by `tools/node_compat/setup.ts`. Do not modify this file manually. + +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); + +const assert = require('assert'); +const crypto = require('crypto'); + +const iv = Buffer.from('00000000000000000000000000000000', 'hex'); +const key = Buffer.from('0123456789abcdef0123456789abcdef' + + '0123456789abcdef0123456789abcdef', 'hex'); + +function encrypt(val, pad) { + const c = crypto.createCipheriv('aes256', key, iv); + c.setAutoPadding(pad); + return c.update(val, 'utf8', 'latin1') + c.final('latin1'); +} + +function decrypt(val, pad) { + const c = crypto.createDecipheriv('aes256', key, iv); + c.setAutoPadding(pad); + return c.update(val, 'latin1', 'utf8') + c.final('utf8'); +} + +// echo 0123456789abcdef0123456789abcdef \ +// | openssl enc -e -aes256 -nopad -K -iv \ +// | openssl enc -d -aes256 -nopad -K -iv +let plaintext = '0123456789abcdef0123456789abcdef'; // Multiple of block size +let encrypted = encrypt(plaintext, false); +let decrypted = decrypt(encrypted, false); +assert.strictEqual(decrypted, plaintext); + +// echo 0123456789abcdef0123456789abcde \ +// | openssl enc -e -aes256 -K -iv \ +// | openssl enc -d -aes256 -K -iv +plaintext = '0123456789abcdef0123456789abcde'; // not a multiple +encrypted = encrypt(plaintext, true); +decrypted = decrypt(encrypted, true); +assert.strictEqual(decrypted, plaintext); diff --git a/tests/unit_node/crypto/crypto_cipher_test.ts b/tests/unit_node/crypto/crypto_cipher_test.ts index d22028624173da..11d643b2c3cf33 100644 --- a/tests/unit_node/crypto/crypto_cipher_test.ts +++ b/tests/unit_node/crypto/crypto_cipher_test.ts @@ -3,7 +3,11 @@ import crypto from "node:crypto"; import { Buffer } from "node:buffer"; import { Readable } from "node:stream"; import { buffer, text } from "node:stream/consumers"; -import { assertEquals, assertThrows } from "@std/assert/mod.ts"; +import { + assertEquals, + assertStrictEquals, + assertThrows, +} from "@std/assert/mod.ts"; const rsaPrivateKey = Deno.readTextFileSync( new URL("../testdata/rsa_private.pem", import.meta.url), @@ -256,3 +260,100 @@ Deno.test({ ); }, }); + +function setAutoPaddingTest( + { algorithm, keyLength, pad }: { + algorithm: string; + keyLength: number; + pad: boolean; + }, +) { + const key = crypto.randomBytes(keyLength); + const iv = algorithm.endsWith("ecb") ? null : crypto.randomBytes(16); + const data = pad + ? "0123456789abcdef0123456789abcde" // Not a multiple of block size + : "0123456789abcdef0123456789abcdef"; // Multiple of block size + + const cipher = crypto.createCipheriv(algorithm, key, iv); + cipher.setAutoPadding(pad); + const encrypted = cipher.update(data, "utf8", "latin1") + + cipher.final("latin1"); + + const decipher = crypto.createDecipheriv(algorithm, key, iv); + decipher.setAutoPadding(pad); + const decrypted = decipher.update(encrypted, "latin1", "utf8") + + decipher.final("utf8"); + + assertStrictEquals(decrypted, data); +} + +/** + * @todo(iuioiua) Add `*-gcm` algorithms once `Cipher.getAuthTag()` and + * `Decipher.setAuthTag()` are implemented. + */ +[ + { + algorithm: "aes-128-cbc", + keyLength: 16, + pad: false, + }, + { + algorithm: "aes-128-cbc", + keyLength: 16, + pad: true, + }, + { + algorithm: "aes-128-ecb", + keyLength: 16, + pad: false, + }, + { + algorithm: "aes-128-ecb", + keyLength: 16, + pad: true, + }, + { + algorithm: "aes-192-ecb", + keyLength: 24, + pad: false, + }, + { + algorithm: "aes-192-ecb", + keyLength: 24, + pad: true, + }, + { + algorithm: "aes256", + keyLength: 32, + pad: false, + }, + { + algorithm: "aes256", + keyLength: 32, + pad: true, + }, + { + algorithm: "aes-256-cbc", + keyLength: 32, + pad: false, + }, + { + algorithm: "aes-256-cbc", + keyLength: 32, + pad: true, + }, + { + algorithm: "aes-256-ecb", + keyLength: 32, + pad: false, + }, + { + algorithm: "aes-256-ecb", + keyLength: 32, + pad: true, + }, +].forEach((options) => { + Deno.test(`cipher.setAutoPadding() and decipher.setAutoPadding() - ${options.algorithm} ${options.pad ? "with" : "without"} padding`, () => { + setAutoPaddingTest(options); + }); +}); diff --git a/tools/node_compat/TODO.md b/tools/node_compat/TODO.md index eb288c65e3a8ae..2eeb4077aeab60 100644 --- a/tools/node_compat/TODO.md +++ b/tools/node_compat/TODO.md @@ -3,7 +3,7 @@ NOTE: This file should not be manually edited. Please edit `tests/node_compat/config.json` and run `deno task setup` in `tools/node_compat` dir instead. -Total: 2999 +Total: 2998 - [abort/test-abort-backtrace.js](https://github.com/nodejs/node/tree/v18.12.1/test/abort/test-abort-backtrace.js) - [abort/test-abort-fatal-error.js](https://github.com/nodejs/node/tree/v18.12.1/test/abort/test-abort-fatal-error.js) @@ -468,7 +468,6 @@ Total: 2999 - [parallel/test-crypto-modp1-error.js](https://github.com/nodejs/node/tree/v18.12.1/test/parallel/test-crypto-modp1-error.js) - [parallel/test-crypto-no-algorithm.js](https://github.com/nodejs/node/tree/v18.12.1/test/parallel/test-crypto-no-algorithm.js) - [parallel/test-crypto-op-during-process-exit.js](https://github.com/nodejs/node/tree/v18.12.1/test/parallel/test-crypto-op-during-process-exit.js) -- [parallel/test-crypto-padding-aes256.js](https://github.com/nodejs/node/tree/v18.12.1/test/parallel/test-crypto-padding-aes256.js) - [parallel/test-crypto-padding.js](https://github.com/nodejs/node/tree/v18.12.1/test/parallel/test-crypto-padding.js) - [parallel/test-crypto-pbkdf2.js](https://github.com/nodejs/node/tree/v18.12.1/test/parallel/test-crypto-pbkdf2.js) - [parallel/test-crypto-private-decrypt-gh32240.js](https://github.com/nodejs/node/tree/v18.12.1/test/parallel/test-crypto-private-decrypt-gh32240.js)