Skip to main content

git_simple_encrypt/crypt/
file.rs

1use std::{
2    fs,
3    io::{Read, Seek, SeekFrom},
4    path::Path,
5};
6
7use chacha20poly1305::{XChaCha20Poly1305, aead::KeyInit};
8use log::{debug, warn};
9use tempfile::NamedTempFile;
10
11use crate::{
12    crypt::{
13        header::{FILE_ID_LEN, FileHeader, HEADER_LEN, MAGIC, SALT_LEN, is_encrypted_version},
14        key::{KeyCache, get_or_derive_key, split_keys},
15        stream::{decrypt_body, encrypt_into},
16    },
17    error::{Error, Result},
18    salt_cache::{CacheRef, CachedEntry},
19};
20
21/// Persist a `NamedTempFile` to `dst` atomically, optionally copying metadata.
22pub(super) fn persist_temp_file(
23    temp_file: NamedTempFile,
24    dst: &Path,
25    metadata_source: Option<&Path>,
26) -> Result<()> {
27    if let Some(src) = metadata_source
28        && let Err(e) = copy_metadata::copy_metadata(src, temp_file.path())
29    {
30        warn!("Could not copy metadata from {}: {}", src.display(), e);
31    }
32    temp_file
33        .persist(dst)
34        .map_err(|e| Error::AtomicPersist(dst.to_path_buf(), e.to_string()))?;
35    Ok(())
36}
37
38/// Encrypt `src` into `dst`.
39pub fn encrypt_file_to(
40    src: &Path,
41    dst: &Path,
42    derived_key: &[u8; 32],
43    salt: [u8; SALT_LEN],
44    file_id: Option<[u8; FILE_ID_LEN]>,
45    zstd: Option<u8>,
46) -> Result<Option<FileHeader>> {
47    let mut src_file = fs::File::open(src)?;
48
49    let mut header_bytes = [0u8; HEADER_LEN];
50    if src_file.read_exact(&mut header_bytes).is_ok()
51        && &header_bytes[0..5] == MAGIC
52        && is_encrypted_version(header_bytes[5])
53    {
54        warn!("Source file already encrypted, skipping: {}", src.display());
55        return Ok(None);
56    }
57    src_file.seek(SeekFrom::Start(0))?;
58
59    debug!("Encrypting {} → {}", src.display(), dst.display());
60
61    let dst_parent = dst.parent().unwrap_or_else(|| Path::new("."));
62    fs::create_dir_all(dst_parent)?;
63    let mut temp_file = NamedTempFile::new_in(dst_parent)?;
64
65    let header = encrypt_into(
66        &mut src_file,
67        &mut temp_file,
68        derived_key,
69        salt,
70        file_id,
71        zstd,
72    )?;
73
74    drop(src_file);
75    persist_temp_file(temp_file, dst, Some(src))?;
76
77    Ok(Some(header))
78}
79
80/// Decrypt `src` into `dst`.
81pub fn decrypt_file_to(src: &Path, dst: &Path, master_key: &[u8]) -> Result<Option<FileHeader>> {
82    let mut src_file = fs::File::open(src)?;
83
84    let mut header_bytes = [0u8; HEADER_LEN];
85    if src_file.read_exact(&mut header_bytes).is_err() {
86        debug!(
87            "File too small to be encrypted, skipping: {}",
88            src.display()
89        );
90        return Ok(None);
91    }
92    if &header_bytes[0..5] != MAGIC || !is_encrypted_version(header_bytes[5]) {
93        debug!("File not encrypted (no magic), skipping: {}", src.display());
94        return Ok(None);
95    }
96
97    debug!("Decrypting {} → {}", src.display(), dst.display());
98
99    let header = *FileHeader::from_bytes(&header_bytes)?;
100    let derived_key = super::key::derive_key(master_key, &header.salt)?;
101
102    let dst_parent = dst.parent().unwrap_or_else(|| Path::new("."));
103    fs::create_dir_all(dst_parent)?;
104    let mut temp_file = NamedTempFile::new_in(dst_parent)?;
105
106    let (key_enc, _) = split_keys(&derived_key);
107    let cipher = XChaCha20Poly1305::new(key_enc.as_ref().into());
108    decrypt_body(&mut src_file, &mut temp_file, &cipher, &header)?;
109
110    drop(src_file);
111    persist_temp_file(temp_file, dst, Some(src))?;
112
113    Ok(Some(header))
114}
115
116/// Encrypt a single file **in place**.
117pub fn encrypt_file(
118    path: &Path,
119    derived_key: &[u8; 32],
120    salt: &[u8; SALT_LEN],
121    file_id: Option<[u8; FILE_ID_LEN]>,
122    zstd: Option<u8>,
123) -> Result<Option<FileHeader>> {
124    encrypt_file_to(path, path, derived_key, *salt, file_id, zstd)
125}
126
127/// Decrypt a single file **in place**.
128pub fn decrypt_file(path: &Path, master_key: &[u8]) -> Result<()> {
129    decrypt_file_to(path, path, master_key).map(|_| ())
130}
131
132/// Decrypt a single file with a thread-safe Argon2 key cache and optional
133/// salt/`file_id` cache.
134pub fn decrypt_file_with_cache(
135    path: &Path,
136    key_cache: &KeyCache,
137    cache: Option<CacheRef<'_>>,
138    master_key: &[u8],
139) -> Result<()> {
140    let mut file = fs::File::open(path)?;
141
142    let mut header_bytes = [0u8; HEADER_LEN];
143    if file.read_exact(&mut header_bytes).is_err() {
144        debug!(
145            "File too small to be encrypted, skipping: {}",
146            path.display()
147        );
148        return Ok(());
149    }
150    if &header_bytes[0..5] != MAGIC || !is_encrypted_version(header_bytes[5]) {
151        debug!(
152            "File not encrypted (no magic), skipping: {}",
153            path.display()
154        );
155        return Ok(());
156    }
157
158    debug!("Decrypting: {}", path.display());
159    let header = *FileHeader::from_bytes(&header_bytes)?;
160
161    if let Some(cache) = cache {
162        cache.sender.insert(
163            cache.key,
164            CachedEntry {
165                salt: header.salt,
166                file_id: header.file_id,
167            },
168        );
169    }
170
171    let derived_key = get_or_derive_key(key_cache, master_key, &header.salt)?;
172
173    let (key_enc, _key_mac) = split_keys(&derived_key);
174    let cipher = XChaCha20Poly1305::new(key_enc.as_ref().into());
175    let parent_dir = path.parent().unwrap_or_else(|| Path::new("."));
176    let mut temp_file = NamedTempFile::new_in(parent_dir)?;
177
178    decrypt_body(&mut file, &mut temp_file, &cipher, &header)?;
179    drop(file);
180
181    persist_temp_file(temp_file, path, Some(path))?;
182
183    Ok(())
184}