hometools

Encrypt a File with a Password in Rust

April 2026

Overview

The Files

src/main.rs

use anyhow::Result;
use orion::{aead, kdf};
use std::fs;
use std::path::PathBuf;

fn main() -> Result<()> {
  let input_path = PathBuf::from("samples/cleartext.txt");
  let output_path = PathBuf::from("samples/encrypted.txt.bin");
  let password = "Correct Horse Battery Staple".to_string();
  let salt = "c72ffc65-3966-481f-ad03-5e7ac42fc3ea".to_string();
  encrypt_file(&input_path, &output_path, &password, &salt)?;
  Ok(())
}

pub fn encrypt_file(
  input_path: &PathBuf,
  output_path: &PathBuf,
  password: &str,
  salt: &str,
) -> Result<()> {
  let input = fs::read(input_path)?;
  let kdf_password =
    kdf::Password::from_slice(password.as_bytes())?;
  let salt = kdf::Salt::from_slice(salt.as_bytes())?;
  let derived_key =
    kdf::derive_key(&kdf_password, &salt, 3, 1 << 8, 32)?;
  let bytes = aead::seal(&derived_key, &input)?;
  fs::write(output_path, bytes)?;
  Ok(())
}

Cargo.toml

[package]
name = "encrypt-a-file-with-a-password"
version = "0.1.0"
edition = "2024"

[dependencies]
anyhow = "1.0.102"
orion = "0.17.13"

References