GenericArray from runtime size


How can we build a GenericArray from a previous Vec<u8> with size known at runtime ?

I've seen this macros :

impl_from! {
    1  => ::typenum::U1,
    2  => ::typenum::U2,
    3  => ::typenum::U3,

So I guess that there is a way for doing so, but I can't figure out how.

For the context, I'm decrypting an AES encoded string, and I'd like to unpad the previous value. It is padded from a number of block size but I can't know the size at compile time :

let padded: Vec<u8> = cipher.decrypt(nonce, ciphered.as_ref()).unwrap();
let padded_array = GenericArray::from(padded.as_slice()); <-- won't compile
let plaintext = Pkcs7::unpad(&padded_array).unwrap();
assert_eq!(&plaintext, b"payload");

it says :

let padded_array = GenericArray::from(padded.as_slice());
   |                            ^^^^^^^^^^^^^^^^^^ the trait `From<&[u8]>` is not implemented for `GenericArray<_, _>`

I have tried a lot of other ways for building the GenericArray but without any success.

Do you have an idea how I could build an array from the padded variable ?

Thank you for your help,


Block size for AES ciphers is fixed and equal to 16 bytes. You should represent the ciphertext as &mut [GenericArray<u8, U16>] (it currently requires unsafe code, but in future we will use as_chunks) and after decrypting blocks you then unpad the last one. The BlockDecryptMut::decrypt_padded* methods already handle this, so I recommend to use them instead of writing such code manually.

Thanks for your reply. I'll have a look on decrypt_padded.

For the array [GenericArray<u8, U16>] that wouldn't help because Pkcs7::unpad function is waiting for a GenericArray type.

Read carefully. I wrote "you then unpad the last one". Also the latest version of the block-padding crate has the Padding::unpad_blocks method.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.