crypto_write_read/
crypto_write_read.rs1use anyhow::Result;
2use rand_core::RngCore;
3use std::env::args;
4use std::fs::File;
5use std::io;
6use std::path::Path;
7
8use shush_rs::SecretVec;
9use tracing::info;
10
11use rencfs::crypto;
12use rencfs::crypto::write::CryptoWrite;
13use rencfs::crypto::Cipher;
14
15fn main() -> Result<()> {
16 tracing_subscriber::fmt().init();
17
18 let cipher = Cipher::ChaCha20Poly1305;
19 let mut key = vec![0; cipher.key_len()];
20 crypto::create_rng().fill_bytes(key.as_mut_slice());
21 let key = SecretVec::from(key);
22
23 let mut args = args();
24 let _ = args.next();
26 let path_in = args.next().expect("path_in is missing");
28 let out = Path::new(&path_in).to_path_buf().with_extension("enc");
30 if out.exists() {
31 std::fs::remove_file(&out)?;
32 }
33
34 let mut file = File::open(path_in.clone())?;
35 let mut writer = crypto::create_write(File::create(out.clone())?, cipher, &key);
36 info!("encrypt file");
37 io::copy(&mut file, &mut writer).unwrap();
38 writer.finish()?;
39
40 let mut reader = crypto::create_read(File::open(out)?, cipher, &key);
41 info!("read file and compare hash to original one");
42 let hash1 = crypto::hash_reader(&mut File::open(path_in)?)?;
43 let hash2 = crypto::hash_reader(&mut reader)?;
44 assert_eq!(hash1, hash2);
45
46 Ok(())
47}