-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencrypt_text_file.rs
73 lines (62 loc) · 2.59 KB
/
encrypt_text_file.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
use std::fs;
use std::io::{self, Read, Write};
fn encrypt(text: &str) -> String {
text.chars()
.map(|c| (c as u8).wrapping_add(1) as char)
.collect()
}
fn decrypt(encrypted_text: &str) -> String {
encrypted_text
.chars()
.map(|c| (c as u8).wrapping_sub(1) as char)
.collect()
}
fn main() {
loop {
println!("Menu:");
println!("1. Encrypt File");
println!("2. Decrypt File");
println!("3. Exit");
let mut choice = String::new();
io::stdin()
.read_line(&mut choice)
.expect("Failed to read line");
match choice.trim() {
"1" => {
println!("Enter the path of the file to encrypt:");
let mut file_path = String::new();
io::stdin()
.read_line(&mut file_path)
.expect("Failed to read line");
let file_path = file_path.trim();
let original_text = fs::read_to_string(&file_path).unwrap_or_else(|_| String::new());
let encrypted_text = encrypt(&original_text);
let encrypted_file_path = format!("{}_encrypted.txt", file_path);
let mut encrypted_file = fs::File::create(&encrypted_file_path).expect("Failed to create file");
encrypted_file.write_all(encrypted_text.as_bytes()).expect("Failed to write to file");
println!("File encrypted and saved to: {}", encrypted_file_path);
}
"2" => {
println!("Enter the path of the file to decrypt:");
let mut file_path = String::new();
io::stdin()
.read_line(&mut file_path)
.expect("Failed to read line");
let file_path = file_path.trim();
let encrypted_text = fs::read_to_string(&file_path).unwrap_or_else(|_| String::new());
let decrypted_text = decrypt(&encrypted_text);
let decrypted_file_path = format!("{}_decrypted.txt", file_path);
let mut decrypted_file = fs::File::create(&decrypted_file_path).expect("Failed to create file");
decrypted_file.write_all(decrypted_text.as_bytes()).expect("Failed to write to file");
println!("File decrypted and saved to: {}", decrypted_file_path);
}
"3" => {
println!("Exiting. Goodbye!");
break;
}
_ => {
println!("Invalid choice. Please enter a number between 1 and 3.");
}
}
}
}