Skip to content

Commit

Permalink
fix: ensure decrypter targeting file shall not be pre-existing
Browse files Browse the repository at this point in the history
  • Loading branch information
maqi authored and joshuef committed Oct 9, 2023
1 parent c8918b7 commit dbeacce
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ use encrypt::encrypt_chunk;
use itertools::Itertools;
use std::{
collections::BTreeMap,
fs::{File, OpenOptions},
fs::{self, File, OpenOptions},
io::{Read, Seek, SeekFrom, Write},
ops::Range,
path::{Path, PathBuf},
Expand Down Expand Up @@ -277,6 +277,11 @@ impl StreamSelfDecryptor {
pub fn decrypt_to_file(file_path: Box<PathBuf>, data_map: &DataMap) -> Result<Self> {
let temp_dir = tempdir()?;
let src_hashes = extract_hashes(data_map);

// The targeted file shall not be pre-exist.
// Hence we carry out a forced removal before carry out any further action.
let _ = fs::remove_file(&*file_path);

Ok(StreamSelfDecryptor {
file_path,
chunk_index: 0,
Expand Down
9 changes: 9 additions & 0 deletions src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,15 @@ fn test_stream_self_encryptor() -> Result<(), Error> {

// Decrypt the shuffled chunks using StreamSelfDecryptor
let decrypted_file_path = dir.path().join("decrypted");

// Write something to the decrypted file first to simulate it's corrupted.
{
let mut file = File::create(&decrypted_file_path)?;
let file_size = 1024; // 1KB
let data = random_bytes(file_size);
file.write_all(&data)?;
}

let mut decryptor =
StreamSelfDecryptor::decrypt_to_file(Box::new(decrypted_file_path.clone()), &data_map)?;
for chunk in encrypted_chunks {
Expand Down

0 comments on commit dbeacce

Please sign in to comment.