rust-pkcs11 icon indicating copy to clipboard operation
rust-pkcs11 copied to clipboard

Change `Ctx::generate_random` to take the buffer to be filled instead of generating the buffer from a given size

Open beamer159 opened this issue 3 years ago • 0 comments

Ctx::generate_random takes in a randomLength: CK_ULONG parameter and uses this to generate a corresponding buffer of the given size, fills it with randomized data, and returns it to the caller. I propose instead letting the caller pass in the buffer directly to the function as a mutable reference, which the function then fills with randomized data.

I prefer this approach because a common use case for this function is to create a custom CryptoRng struct from the rand crate. To implement this trait includes implementing these functions:

  • fn fill_bytes(&mut self, dest: &mut [u8])
  • fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error>

Both functions already include the buffer to be filled. Currently, implementing these functions using Ctx::generate_random results in an unnecessary allocation of the same size as the dest buffer, which then needs to be copied over.

My main concern with this proposed change is that C_GenerateRandom can only fill a buffer up to CK_ULONG size, which is smaller than usize, the maximum buffer size. Therefore, the buffer size may need to be checked before calling C_GenerateRandom.

beamer159 avatar Jan 07 '22 22:01 beamer159