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

feat(node): crypto.{Cipheriv,Decipheriv}.setAutoPadding() #22228

Closed
wants to merge 21 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
222 changes: 162 additions & 60 deletions ext/node/ops/crypto/cipher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,11 +67,12 @@ impl CipherContext {
self,
input: &[u8],
output: &mut [u8],
auto_padding: bool,
) -> Result<Tag, AnyError> {
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)
}
}

Expand All @@ -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)
}
}

Expand Down Expand Up @@ -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<Tag, AnyError> {
fn r#final(
self,
input: &[u8],
output: &mut [u8],
auto_padding: bool,
) -> Result<Tag, AnyError> {
assert!(input.len() < 16);
use Cipher::*;
match self {
Aes128Cbc(encryptor) => {
let _ = (*encryptor)
.encrypt_padded_b2b_mut::<Pkcs7>(input, output)
.map_err(|_| type_error("Cannot pad the input data"))?;
Aes128Cbc(mut encryptor) => {
if auto_padding {
let _ = (*encryptor)
.encrypt_padded_b2b_mut::<Pkcs7>(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::<Pkcs7>(input, output)
.map_err(|_| type_error("Cannot pad the input data"))?;
Aes128Ecb(mut encryptor) => {
if auto_padding {
let _ = (*encryptor)
.encrypt_padded_b2b_mut::<Pkcs7>(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::<Pkcs7>(input, output)
.map_err(|_| type_error("Cannot pad the input data"))?;
Aes192Ecb(mut encryptor) => {
if auto_padding {
let _ = (*encryptor)
.encrypt_padded_b2b_mut::<Pkcs7>(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::<Pkcs7>(input, output)
.map_err(|_| type_error("Cannot pad the input data"))?;
Aes256Ecb(mut encryptor) => {
if auto_padding {
let _ = (*encryptor)
.encrypt_padded_b2b_mut::<Pkcs7>(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::<Pkcs7>(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::<Pkcs7>(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)
}
}
Expand Down Expand Up @@ -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::<Pkcs7>(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::<Pkcs7>(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::<Pkcs7>(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::<Pkcs7>(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::<Pkcs7>(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::<Pkcs7>(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::<Pkcs7>(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::<Pkcs7>(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::<Pkcs7>(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::<Pkcs7>(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(())
}
}
Expand Down
6 changes: 4 additions & 2 deletions ext/node/ops/crypto/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -292,11 +292,12 @@ pub fn op_node_cipheriv_final(
#[smi] rid: u32,
#[buffer] input: &[u8],
#[buffer] output: &mut [u8],
auto_padding: bool,
) -> Result<Option<Vec<u8>>, AnyError> {
let context = state.resource_table.take::<cipher::CipherContext>(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)]
Expand Down Expand Up @@ -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::<cipher::DecipherContext>(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]
Expand Down
20 changes: 15 additions & 5 deletions ext/node/polyfills/internal/crypto/cipher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand All @@ -166,6 +167,8 @@ export class Cipheriv extends Transform implements Cipher {

#authTag?: Buffer;

#autoPadding: boolean;

constructor(
cipher: string,
key: CipherKey,
Expand All @@ -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 {
Expand All @@ -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);
Expand All @@ -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;
}

Expand Down Expand Up @@ -309,6 +314,8 @@ export class Decipheriv extends Transform implements Cipher {

#authTag?: BinaryLike;

#autoPadding: boolean;

constructor(
cipher: string,
key: CipherKey,
Expand All @@ -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 {
Expand All @@ -342,6 +350,7 @@ export class Decipheriv extends Transform implements Cipher {
this.#cache.cache,
buf,
this.#authTag || NO_TAG,
this.#autoPadding,
Comment on lines 351 to +353
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The tests are failing because buf is a fixed buffer of size 16 (block size).

When auto padding is disabled, buf should be sliced from (0, len] where len is the length of the unpadded block returned by decrypt_block_b2b_mut

);

if (!this.#needsBlockCache) {
Expand All @@ -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(
Expand Down
Loading