doby/src/main.rs

87 lines
3.9 KiB
Rust
Raw Permalink Normal View History

2021-11-13 19:34:46 +01:00
use std::{process, io::{BufReader, Read}};
2021-06-25 23:01:50 +02:00
use doby::{
cli,
2021-06-27 20:35:23 +02:00
crypto::{EncryptionParams, DobyCipher},
2021-06-25 23:01:50 +02:00
MAGIC_BYTES,
decrypt,
encrypt,
};
2021-11-13 19:08:28 +01:00
use zeroize::Zeroize;
2021-06-25 23:01:50 +02:00
2021-07-04 18:33:59 +02:00
fn run() -> bool {
let mut success = false;
2021-11-13 19:34:46 +01:00
if let Some(result) = cli::parse() {
if let Some(cli_args) = result.cli_args {
let mut reader = BufReader::new(cli_args.reader);
2021-07-04 16:24:44 +02:00
2021-11-13 19:34:46 +01:00
let mut magic_bytes = vec![0; MAGIC_BYTES.len()];
match reader.read(&mut magic_bytes) {
Ok(n) => {
if magic_bytes == MAGIC_BYTES && !cli_args.force_encrypt { //we probably want to decrypt
match EncryptionParams::read(&mut reader) {
Ok(params) => {
if let Some(params) = params {
2021-11-13 19:08:28 +01:00
if let Some(mut password) = cli_args.password.get(false) {
2021-11-13 19:34:46 +01:00
if let Some(mut writer) = cli_args.writer.into_buf_writer() {
let cipher = DobyCipher::new(password.as_bytes(), &params);
password.zeroize();
match decrypt(&mut reader, &mut writer, cipher, cli_args.block_size) {
Ok(verified) => {
if verified {
success = true
} else {
eprintln!("Warning: HMAC verification failed !\nEither your password is incorrect or the ciphertext has been corrupted.\nBe careful, the data could have been altered by an attacker.");
}
2021-06-27 20:35:23 +02:00
}
2021-11-13 19:34:46 +01:00
Err(e) => eprintln!("I/O error while decrypting: {}", e)
2021-06-25 23:01:50 +02:00
}
2021-11-13 19:34:46 +01:00
} else {
password.zeroize();
2021-06-25 23:01:50 +02:00
}
}
2021-11-13 19:34:46 +01:00
} else {
2021-11-16 19:07:18 +01:00
eprintln!("Error: invalid encryption parameters")
2021-06-25 23:01:50 +02:00
}
}
2021-11-13 19:34:46 +01:00
Err(e) => eprintln!("I/O error while reading headers: {}", e)
2021-06-25 23:01:50 +02:00
}
2021-11-13 19:34:46 +01:00
} else { //otherwise, encrypt
let params = EncryptionParams::new(cli_args.argon2_params, cli_args.cipher);
if let Some(mut password) = cli_args.password.get(true) {
if let Some(mut writer) = cli_args.writer.into_buf_writer() {
let cipher = DobyCipher::new(password.as_bytes(), &params);
password.zeroize();
match encrypt(
&mut reader,
&mut writer,
&params,
cipher,
cli_args.block_size,
Some(&magic_bytes[..n])
) {
Ok(_) => success = true,
Err(e) => eprintln!("I/O error while encrypting: {}", e)
}
} else {
password.zeroize();
}
2021-06-25 23:01:50 +02:00
}
}
}
2021-11-13 19:34:46 +01:00
Err(e) => eprintln!("I/O error while reading magic bytes: {}", e),
2021-06-25 23:01:50 +02:00
}
2021-11-13 19:34:46 +01:00
} else {
success = !result.error;
2021-06-25 23:01:50 +02:00
}
}
2021-07-04 18:33:59 +02:00
success
}
fn main() {
process::exit(if run() {
0
} else {
1
});
2021-06-25 23:01:50 +02:00
}