How to securely erase a vec?

The Vec documentation states

Do not rely on removed data to be erased for security purposes. Even if you drop a Vec , its buffer may simply be reused by another Vec . Even if you zero a Vec 's memory first, that may not actually happen because the optimizer does not consider this a side-effect that must be preserved.

If I wanted to guarantee the information in a Vec is erased, but zeroing it may be ignored, how would I do it?

You can use write_volatile, or you can just use clear_on_drop crate. But note that this solution is not perfect, e.g. because user always can call mem::forget on your data, also read this discussion:


This is very, very hard. To do it fully, one must also, for example, keep the OS from ever swapping that memory to disk while it contains the secret.

1 Like

Also take into account that during the usage of the vector it might change sizes, which will imply reallocation, thus you’ll leak non-zeroed data.

Thus the best solution is to pre-allocate it. In terms of Rust structures the best alternative (which will stop you from resizing it is Box<[Element]> which can be obtained by Vec::with_capacity(size).into_boxed_slice().

1 Like

Minor note: This will create a boxed slice with length zero, because into_boxed_slice drops the excess capacity. You’ll need to initialize the items in the Vec before converting it to a Box.

The seckey crate which is built on the memsec crate is also a good option for clearing data. memsec and seckey also provide mlock for systems that support this, to avoid memory being written to swap. I don’t know which functionality is offered in case of mlock if the system is not Linux. memsec is a

“Rust implementation libsodium/utils.”

I’ve had no issues with those two crates, can recommend.