diff --git a/src/lib.rs b/src/lib.rs index bdcf2b2b8..d70176c50 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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}, @@ -277,6 +277,11 @@ impl StreamSelfDecryptor { pub fn decrypt_to_file(file_path: Box, data_map: &DataMap) -> Result { 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, diff --git a/src/tests.rs b/src/tests.rs index d8a0844fb..92a2b1408 100644 --- a/src/tests.rs +++ b/src/tests.rs @@ -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 {