Skip to main content

secure_vec

Function secure_vec 

Source
pub fn secure_vec<T: Default + Clone>(size: usize) -> Result<SecureVec<T>>
Expand description

Create a new secure vector with enhanced memory protection

This function creates a new SecureVec<T> with comprehensive memory protection features designed for storing sensitive cryptographic material.

§Security Features

  • Secure Allocation: Uses libsodium’s sodium_malloc() for memory allocation with guard pages
  • Overflow Detection: Canary values and guard pages detect buffer overflows and underflows
  • Memory Locking: Allocated memory is locked to prevent it from being swapped to disk
  • Automatic Zeroing: Memory is automatically and securely zeroed when freed
  • Use-after-free Protection: Helps mitigate use-after-free vulnerabilities

§Performance Considerations

  • Secure memory allocation has higher overhead than standard allocation
  • Memory is page-aligned, which may use more memory than strictly necessary
  • The memory locking feature may be subject to system-wide limits

§Error Handling

This function returns an io::Result<SecureVec<T>> which will be an error if:

  • The system has insufficient memory
  • The process has reached its limit for locked memory
  • The secure memory allocation fails for any other reason

§Example

use libsodium_rs as sodium;
use libsodium_rs::utils::vec_utils;
use sodium::ensure_init;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    ensure_init()?;

    // Create a secure vector
    let mut secure_vec = vec_utils::secure_vec::<u8>(32)?;

    // Use it like a regular vector
    for i in 0..secure_vec.len() {
        secure_vec[i] = i as u8;
    }

    // When it goes out of scope, memory is automatically zeroed and freed
    Ok(())
}

§Arguments

  • size - The initial size of the vector

§Returns

  • io::Result<SecureVec<T>> - A new secure vector or an error if allocation failed