How to Handle Secrets and Sensitive Data in Rust (secrecy crate)

Use the Rust `secrecy` crate to wrap sensitive data in a type that prevents accidental logging or printing at compile time.

Use the secrecy crate to wrap sensitive values in a Secret type that prevents accidental logging or printing. Add the dependency, import the macro, and wrap your data to enforce compile-time safety against leaks.

use secrecy::{Secret, ExposeSecret};

fn main() {
    let password = Secret::new("hunter2".to_string());
    // println!("Password: {}", password); // Compile error!
    let exposed: &str = password.expose_secret();
    println!("Password: {}", exposed); // Explicit access only
}
  1. Add the crate to your Cargo.toml file. cargo add secrecy
  2. Import the Secret struct and ExposeSecret trait in your source file. use secrecy::{Secret, ExposeSecret};
  3. Wrap your sensitive string or value using the Secret::new constructor. let secret = Secret::new("my_password".to_string());
  4. Access the underlying value only when explicitly needed using the expose_secret method. let plain = secret.expose_secret();
  5. Attempting to print or format the Secret directly will now fail at compile time. // println!("{}", secret); // Error: Secret does not implement Display