Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: ensure decrypter targeting file shall not be pre-existing #373

Merged
merged 1 commit into from
Oct 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading