nutek-cipher 2.0.7

Encrypt and decrypt files and text with ease
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
extern crate aes_gcm_siv;
use aes_gcm_siv::aead::consts::U12;

use aes_gcm_siv::aead::generic_array::GenericArray;
use clap::Parser;
use rand::Rng;
use std::fs::File;
use std::io::{self, BufRead, BufReader, BufWriter, Read, Write};
use std::process::exit;
mod cli;
use aes_gcm_siv::{
    aead::{Aead, KeyInit},
    Aes256GcmSiv,
    Key, // Or `Aes128GcmSiv`
    Nonce,
};
use std::env;
use std::thread::sleep;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use text_io::read;

fn decrypt(key_slice: &[u8], nonce_slice: &[u8], ciphertext: Vec<u8>) -> Option<Vec<u8>> {
    let key = Key::<Aes256GcmSiv>::from_slice(key_slice);
    let cipher = Aes256GcmSiv::new(&key);
    let nonce: &GenericArray<u8, U12> = Nonce::from_slice(nonce_slice);
    let plaintext = cipher.decrypt(nonce, ciphertext.as_ref()).ok()?;
    println!("Successfuly decrypted ciphertext");
    Some(plaintext)
}

fn encrypt(plaintext: &[u8], nonce_slice: &[u8], key_slice: &[u8]) -> Vec<u8> {
    let key = Key::<Aes256GcmSiv>::from_slice(key_slice);
    let cipher = Aes256GcmSiv::new(&key);
    let nonce: &GenericArray<u8, U12> = Nonce::from_slice(nonce_slice);
    let ciphertext = cipher.encrypt(nonce, plaintext.as_ref()).unwrap();
    if ciphertext.len() == 0 {
        panic!("❌ Ciphertext is empty");
    } else if ciphertext.len() > aes_gcm_siv::C_MAX.try_into().unwrap() {
        println!("❌ Ciphertext is too long");
    }
    println!("Successfuly encrypted plaintext");
    ciphertext
}

fn key_and_nonce_warning() {
    // print warning to protect key and nonce, and tell user they are
    // responsible for keeping them safe and not losing them
    // because they are not stored anywhere and not recoverable
    // also needed to decrypt the data
    println!("💥❗️  WARNING: You are responsible for keeping your 🔑 key and 🔑 nonce safe and not losing them. They are not stored anywhere and not recoverable. You will need them to decrypt your data.\nUse --save-codes to save codes to ONE file! distribute them as you wish...");
}

fn virtual_money() {
    println!("\nThank you for using nutek-cipher 🔐 - safe encryption for your daily use");
}

fn nuteksecurity_address() {
    println!("\nhttps://nuteksecurity.com");
    println!("neosb@nuteksecurity.com");
}

fn get_home_dir() -> String {
    // Check for HOME on Unix-like systems first
    if cfg!(target_os = "windows") {
        // On Windows, use USERPROFILE
        env::var("USERPROFILE").unwrap_or_else(|_| {
            println!("'USERPROFILE' environment variable not found.");
            String::new()
        })
    } else {
        env::var("HOME").unwrap_or_else(|_| {
            println!("'HOME' environment variable not found.");
            String::new()
        })
    }
}

fn save_codes_file(password: String, nonce: String, test: bool) -> String {
    // save key and nonce to file in format
    // key=12345678123456781234567812345678
    // nonce=123456123456
    // with name as UNIX timestamp
    let now = SystemTime::now();
    let home_dir = get_home_dir();
    let mut codes_file = format!(
        "{}/Downloads/{}.codes",
        home_dir,
        now.duration_since(UNIX_EPOCH)
            .expect("Time went backwards")
            .as_nanos()
    );
    if test {
        codes_file = format!(
            "{}.codes",
            now.duration_since(UNIX_EPOCH)
                .expect("Time went backwards")
                .as_nanos()
        );
    }

    match File::open(&codes_file) {
        Ok(_) => {
            eprintln!("Codes file with the same name already exist. Waiting some time...");
            let delay_duration = Duration::from_nanos(10 * 1000 * 1000); // 10 milliseconds
            sleep(delay_duration);
            println!("Delay completed!");
            return save_codes_file(password, nonce, test);
        }
        Err(_) => {
            // Handle error here, e.g., log an error and return or panic
            // println!("Error opening file: {}", error);
            let mut codes_file_buf = BufWriter::new(File::create(&codes_file).unwrap());
            codes_file_buf
                .write_all(
                    format!(
                        "key={}
nonce={}
",
                        password, nonce
                    )
                    .as_bytes(),
                )
                .unwrap();
            println!("🔑 Written key and nonce to: {}", &codes_file);
            return codes_file;
        }
    }
}

fn sum_codes_to_file(sum_codes: String, test: bool) -> String {
    if !sum_codes.contains(":") {
        panic!("🙀 error: --sum-codes should be a path separated with ':' - key.file_path:nonce.file_path")
    }

    // Split the input string into an iterator over substrings separated by ":"
    let mut sums_array = sum_codes.split(':').map(|s| s.to_owned());

    // Get the key path from the first element of the iterator
    let key_path = sums_array.next().unwrap();

    // Get the nonce path from the second element of the iterator
    let nonce_path = sums_array.next().unwrap();

    let mut key = String::new();
    match File::open(&key_path) {
        Ok(file) => {
            // Code here will only run if file was successfully opened
            let mut reader = BufReader::new(file);
            reader.read_line(&mut key).unwrap();
            if key.starts_with("key=") {
                let shorter = key[4..].to_string();
                key = shorter;
            }
        }
        Err(error) => {
            // Handle error here, e.g., log an error and return or panic
            println!("Error opening file: {}", error);
        }
    }

    let mut nonce = String::new();
    match File::open(&nonce_path) {
        Ok(file) => {
            // Code here will only run if file was successfully opened
            let mut reader = BufReader::new(file);
            reader.read_line(&mut nonce).unwrap();
            if nonce.starts_with("key=") {
                let shorter = nonce[6..].to_string();
                nonce = shorter;
            }
        }
        Err(error) => {
            // Handle error here, e.g., log an error and return or panic
            println!("Error opening file: {}", error);
        }
    }

    assert_eq!(key.len(), 32, "❌ Key must be 32 characters long");
    assert_eq!(nonce.len(), 12, "❌ Nonce must be 12 characters long");
    // save key and nonce to file in format
    // key=12345678123456781234567812345678
    // nonce=123456123456
    // with name  as UNIX timestamp

    let codes_file = save_codes_file(key, nonce, test);

    if !test {
        exit(0)
    } else {
        return codes_file;
    }
}

fn main() {
    // max 65,536 MB

    let cli = cli::Cli::parse();

    let stdin = io::stdin();
    let handle = stdin.lock();
    let lines = handle.lines();
    // unwrap lines
    let lines = lines.map(|line| line.unwrap());
    // let lines = lines.peekable()

    let mut key = String::new();
    let mut nonce = String::new();

    if let Some(sum_codes) = cli.sum_codes {
        sum_codes_to_file(sum_codes, false);
    }

    let codes_file = cli.codes_file.unwrap_or("".to_string());
    if codes_file != "" {
        let mut file = File::open(codes_file).expect("❌ can't open codes file");
        let mut codes = String::new();
        file.read_to_string(&mut codes)
            .expect("❌ can't read codes file");
        codes = codes.trim().to_string();
        let codes = codes.split("\n");
        for code in codes {
            let code_split = code.split("=");
            let code_split: Vec<&str> = code_split.collect();
            let code = code_split.get(1).unwrap_or(&"");
            let code = code.trim();
            let test = code_split.get(0).unwrap_or(&"");
            if test == &"key" {
                key = code.to_string();
            } else if test == &"nonce" {
                nonce = code.to_string();
            }
        }
    }

    if cli.display_codes {
        println!("🔑 Key: {}", key);
        println!("🔑 Nonce: {}", nonce);
        exit(0)
    }

    if cli.random_codes {
        key = rand::thread_rng()
            .sample_iter(&rand::distributions::Alphanumeric)
            .take(32)
            .map(char::from)
            .collect();
        nonce = rand::thread_rng()
            .sample_iter(&rand::distributions::Alphanumeric)
            .take(12)
            .map(char::from)
            .collect();
    }

    if key != "" && nonce != "" {
        assert_eq!(key.len(), 32, "❌ Key must be 32 characters long");
        assert_eq!(nonce.len(), 12, "❌ Nonce must be 12 characters long");
    } else {
        key = rpassword::prompt_password("🔑 Your key [32 characters]: ").unwrap();
        nonce = rpassword::prompt_password("🔑 Your nonce [12 characters]: ").unwrap();
    }

    assert_eq!(key.len(), 32, "❌ Key must be 32 characters long");
    assert_eq!(nonce.len(), 12, "❌ Nonce must be 12 characters long");

    let stdout = cli.stdout;

    let input_file = cli.input_file.unwrap_or("".to_string());

    let output_file = cli.output_file.unwrap_or("".to_string());

    // if lines.peek().is_some() {
    println!("📝 Processing input from user...");
    if input_file != "" {
        println!("📝 Input file: {}", input_file);
        if stdout || output_file != "" {
            if cli.encrypt == true {
                println!("🔐 Encrypting file mode on... Proceeding...");
                encrypt_file(
                    input_file,
                    output_file,
                    &key,
                    &nonce,
                    stdout,
                    cli.save_codes,
                    false,
                )
                .expect("can't encrypt");
                key_and_nonce_warning();
                virtual_money();
                nuteksecurity_address();
            } else if cli.decrypt == true {
                println!("🔓 Decrypting file mode on... Proceeding...");

                decrypt_file(input_file, output_file, &key, &nonce, stdout).expect("can't decrypt");

                virtual_money();
                nuteksecurity_address();
            } else {
                println!("❌ Invalid mode. Must be --encrypt or --decrypt");
            }
        } else {
            println!("❌ I must have either --output-file or --stdout");
        }
        exit(0);
    }
    if stdout || output_file != "" {
        if cli.encrypt == true {
            println!("🔐 Encrypting from pipe - use cat, echo, etc... [⏎ Enter] & CTRL+D (Unix) & [⏎ Enter] CTRL+Z (Windows) to continue with text you input below...");
            let mut stdin = String::new();

            for line in lines {
                if stdin != "" {
                    stdin = format!("{}\n{}", stdin, line);
                } else {
                    if line == "" {
                        println!("❌ No input");
                        exit(1);
                    }
                    stdin = format!("{}", line);
                }
            }

            // convert to UTF-8
            if stdin == "" {
                println!("❌ No input");
                let _line: String = read!("{}");
                exit(1);
            }
            if stdin.len() > aes_gcm_siv::P_MAX.try_into().unwrap() {
                println!(
                    "❌ Input is too long. Maximum is {} characters",
                    aes_gcm_siv::P_MAX
                );
                return;
            }
            println!(
                "📝 Successfully read {} characters from stdin... Continuing with encryption...",
                stdin.len()
            );

            encrypt_stdin(
                stdin,
                output_file,
                stdout,
                &key,
                &nonce,
                cli.save_codes,
                false,
            )
            .expect("can't encrypt");
            key_and_nonce_warning();
            virtual_money();
            nuteksecurity_address();
        } else if cli.decrypt == true {
            println!("🔐 Decrypting stdin mode on... Proceeding...");
            let mut stdin = String::new();
            for line in lines {
                if stdin != "" {
                    stdin = format!("{}\n{}", stdin, line);
                } else {
                    if line == "" {
                        println!("❌ No input");
                        exit(1);
                    }
                    stdin = format!("{}", line);
                }
            }
            if stdin == "" {
                println!("❌ No input");
                exit(1);
            }
            if stdin.len() > aes_gcm_siv::C_MAX.try_into().unwrap() {
                println!(
                    "❌ Input is too long. Maximum is {} characters",
                    aes_gcm_siv::C_MAX
                );
                return;
            }
            println!(
                "📝 Successfully read {} characters from stdin... Continuing...",
                stdin.len()
            );

            decrypt_stdin(stdin, output_file, stdout, &key, &nonce).expect("can't decrypt");

            virtual_money();
            nuteksecurity_address();
        } else {
            println!("❌ Invalid mode. Must be --encrypt or --decrypt");
        }
    } else {
        println!("❌ I must have either --output-file or --stdout");
    }
}

fn encrypt_stdin(
    cleartext: String,
    output_file: String,
    stdout: bool,
    password: &str,
    nonce: &str,
    should_save_codes: bool,
    test: bool,
) -> Result<String, Box<dyn std::error::Error>> {
    println!("🔐 Encrypting...");
    let encrypted_content = encrypt(cleartext.as_bytes(), nonce.as_bytes(), password.as_bytes());
    println!("✅ Done!");
    if output_file != "" {
        // Write the encrypted contents to the output file
        let file = output_file.clone();
        let mut output_file_buf = BufWriter::new(File::create(output_file)?);
        output_file_buf.write_all(&encrypted_content)?;
        println!("Wrote encrypted content to: {}", file);
    }

    if stdout {
        let encoded = hex::encode(encrypted_content);
        println!("🔐 Ciphertext: \n{}", encoded);
        println!("🔑 Nonce: \n{}", nonce);
        println!("🔑 Key: \n{}", password);
    }

    let mut codes_file: String = String::new();
    if should_save_codes {
        codes_file = save_codes_file(password.to_string(), nonce.to_string(), test);
    }

    Ok(codes_file)
}

fn decrypt_stdin(
    ciphertext: String,
    output_file: String,
    stdout: bool,
    password: &str,
    nonce: &str,
) -> Result<(), Box<std::io::Error>> {
    println!("🔓 Decrypting...");
    let decoded = hex::decode(ciphertext).unwrap();
    println!("✅ Done!");
    // Decrypt the contents
    let decrypted_contents = decrypt(password.as_bytes(), nonce.as_bytes(), decoded);

    if let Some(decrypted_contents) = decrypted_contents {
        if output_file != "" {
            // Write the decrypted contents to the output file
            let file = output_file.clone();
            let mut output_file_buf = BufWriter::new(File::create(output_file)?);
            output_file_buf.write_all(&decrypted_contents)?;
            println!("📝 Written decrypted content to {}", file);
        }

        if stdout {
            println!(
                "📝 Plaintext: \n{}",
                String::from_utf8_lossy(&decrypted_contents)
            );
        }
    } else {
        println!("❌ Decryption failed. Wrong 🔑 key, 🔑 nonce or 🥷 empty?");
        return Err::<(), Box<std::io::Error>>(Box::new(std::io::Error::new(
            std::io::ErrorKind::Other,
            "Decryption failed. Wrong key, nonce or empty?",
        )));
    }

    Ok(())
}

fn encrypt_file(
    input_file: String,
    output_file: String,
    password: &str,
    nonce: &str,
    stdout: bool,
    should_save_codes: bool,
    test: bool,
) -> Result<String, Box<dyn std::error::Error>> {
    // Read the input file
    let mut input_file = BufReader::new(File::open(input_file)?);
    let mut input_contents = Vec::new();
    input_file.read_to_end(&mut input_contents)?;
    println!(
        "📝 Successfully read {} characters from file... Continuing...",
        input_contents.len()
    );

    // Encrypt the input contents
    println!("🔐 Encrypting...");
    let encrypted_content = encrypt(&input_contents, nonce.as_bytes(), password.as_bytes());
    println!("✅ Done!");

    // clone to check if output file is not empty string or is empty string
    let output_file_is_not_none = output_file.clone();
    let output_file_is_none = output_file.clone();

    if output_file_is_not_none != "" {
        // Write the encrypted contents to the output file
        let file = output_file.clone();
        let mut output_file_buf = BufWriter::new(File::create(output_file)?);
        output_file_buf.write_all(&encrypted_content)?;
        println!("Wrote encrypted content to: {}", file);
    }

    let encoded = hex::encode(encrypted_content);
    if stdout && encoded.len() <= 4800 {
        println!("🔐 Ciphertext: \n{}", encoded);
        println!("🔑 Nonce: \n{}", nonce);
        println!("🔑 Key: \n{}", password);
    } else if stdout && encoded.len() > 4800 && output_file_is_none == "" {
        println!("🔐 Ciphertext: \nToo long to display... {} characters; Maybe you want to write it to file? Use -o or --output", encoded.len());
        println!("🔑 Nonce: \n{}", nonce);
        println!("🔑 Key: \n{}", password);
    } else if stdout && encoded.len() > 4800 {
        println!(
            "🔐 Ciphertext: \nToo long to display... {} characters;",
            encoded.len()
        );
        println!("🔑 Nonce: \n{}", nonce);
        println!("🔑 Key: \n{}", password);
    }

    let mut codes_file: String = String::new();
    if should_save_codes {
        codes_file = save_codes_file(password.to_string(), nonce.to_string(), test);
    }

    Ok(codes_file)
}

fn decrypt_file(
    input_file: String,
    output_file: String,
    password: &str,
    nonce: &str,
    stdout: bool,
) -> Result<(), Box<std::io::Error>> {
    // Read the encrypted file back in
    let mut encrypted_file = BufReader::new(File::open(input_file)?);
    let mut encrypted_contents = Vec::new();
    encrypted_file.read_to_end(&mut encrypted_contents)?;
    println!(
        "📝 Successfully read {} characters from file... Continuing...",
        encrypted_contents.len()
    );

    // Decrypt the contents
    println!("🔓 Decrypting...");
    let decrypted_content = decrypt(password.as_bytes(), nonce.as_bytes(), encrypted_contents);
    println!("✅ Done!");
    if let Some(decrypted_content) = decrypted_content {
        // clone to check if output file is not empty string or is empty string
        let output_file_is_not_none = output_file.clone();
        let output_file_is_none = output_file.clone();

        if output_file_is_not_none != "" {
            // Write the decrypted contents to the output file
            let file = output_file.clone();
            let mut output_file_buf = BufWriter::new(File::create(output_file)?);
            output_file_buf.write_all(&decrypted_content)?;
            println!("📝 Written decrypted content to {}", file);
        }

        let decrypted_content = String::from_utf8_lossy(&decrypted_content);
        if stdout && decrypted_content.len() <= 4800 {
            println!("📝 Plaintext: \n{}", decrypted_content);
        } else if stdout && decrypted_content.len() > 4800 && output_file_is_none == "" {
            println!("📝 Plaintext: \nToo long to display... {} characters; Maybe you want to write it to file? Use -o or --output", decrypted_content.len());
        } else if stdout && decrypted_content.len() > 4800 {
            println!(
                "📝 Plaintext: \nToo long to display... {} characters;",
                decrypted_content.len()
            );
        }
    } else {
        println!("❌ Decryption failed. Wrong 🔑 key, 🔑 nonce or 🥷 empty?");
        return Err::<(), Box<std::io::Error>>(Box::new(std::io::Error::new(
            std::io::ErrorKind::Other,
            "Decryption failed. Wrong key, nonce or empty?",
        )));
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;

    #[test]
    fn test_encrypt_decrypt() {
        let key = b"12345678123456781234567812345678"; // rand::thread_rng().sample_iter(&rand::distributions::Alphanumeric).take(32).map(char::from).collect();
        let nonce = b"123456123456"; // rand::thread_rng().sample_iter(&rand::distributions::Alphanumeric).take(12).map(char::from).collect();
        let plaintext = b"hello world";

        // let ciphertext = encrypt(key, nonce, plaintext);
        let ciphertext = encrypt(plaintext, nonce, key);
        let decrypted_content = decrypt(key, nonce, ciphertext).unwrap();

        assert_eq!(plaintext, &decrypted_content[..]);
    }

    #[test]
    fn test_encrypt_stdin() {
        let cleartext = "hello world".to_string();
        let output_file = "test_output_encrypt_stdin.txt".to_string();
        let stdout = true;
        let password = "0123456789abcdef0123456789abcdef";
        let nonce = "0123456789ab";

        let output_file_clone = output_file.clone();
        let result = encrypt_stdin(
            cleartext,
            output_file_clone,
            stdout,
            password,
            nonce,
            true,
            true,
        );

        assert!(result.is_ok());

        let ciphertext = "d3de9dbdab9968e05220720f20379ae35ba6c90e3196967adb1f2d";

        // Check that the output file contains the encrypted content
        let output_file_clone = output_file.clone();
        let decrypted_content = fs::read(&output_file_clone).unwrap();
        let decrypted_content_encoded = hex::encode(decrypted_content.clone());
        assert_eq!(decrypted_content_encoded, ciphertext);

        // Clean up the test input and output files
        fs::remove_file(&output_file).unwrap();

        let codes_file = result.unwrap();

        let file_name_path = &codes_file;
        let codes_opened = fs::read_to_string(&file_name_path).unwrap();
        fs::remove_file(file_name_path).unwrap();

        assert!(codes_opened.contains(password));
        assert!(codes_opened.contains(nonce));
    }

    #[test]
    fn test_decrypt_stdin() {
        let ciphertext2 = "d3de9dbdab9968e05220720f20379ae35ba6c90e3196967adb1f2d".to_string();
        let output_file = "test_output_decrypt_stdin.txt".to_string();
        let stdout = true;
        let password = "0123456789abcdef0123456789abcdef";
        let nonce = "0123456789ab";

        let output_file_clone = output_file.clone();
        let decrypted_contents = decrypt_stdin(ciphertext2, output_file, stdout, password, nonce);

        // Check that function returned Ok
        assert!(decrypted_contents.is_ok());

        // Check that the output file was created and contains decrypted content
        let decrypted_content = fs::read(&output_file_clone).unwrap();
        assert_eq!(decrypted_content, "hello world".as_bytes());

        // Clean up the test input and output files
        fs::remove_file(&output_file_clone).unwrap();
    }

    #[test]
    fn test_encrypt_file() {
        let input_file = "test_input_encrypt_file.txt".to_string();
        let output_file = "test_output_encrypt_file.txt".to_string();
        let password = "0123456789abcdef0123456789abcdef";
        let nonce = "0123456789ab";
        let stdout = false;

        // Create a test input file
        fs::write(&input_file, "hello world").unwrap();

        // Call the encrypt_file function
        let result = encrypt_file(
            input_file.clone(),
            output_file.clone(),
            password,
            nonce,
            stdout,
            true,
            true,
        );

        // Check that the function completed successfully
        assert!(result.is_ok());

        // Check that the output file was created and contains encrypted content
        let encrypted_content = fs::read(&output_file).unwrap();
        assert!(encrypted_content.len() > 0);

        // Clean up the test input and output files
        fs::remove_file(&input_file).unwrap();
        fs::remove_file(&output_file).unwrap();

        let codes_file = result.unwrap();

        let file_name_path = &codes_file;
        let codes_opened = fs::read_to_string(&file_name_path).unwrap();
        fs::remove_file(file_name_path).unwrap();

        assert!(codes_opened.contains(password));
        assert!(codes_opened.contains(nonce));
    }

    #[test]
    fn test_decrypt_file() {
        let input_file = "test_input_decrypt_file.txt".to_string();
        let output_file = "test_output_decrypt_file.txt".to_string();
        let password = "0123456789abcdef0123456789abcdef";
        let nonce = "0123456789ab";
        let stdout = false;

        // Create a test input file
        let encrypted_content = encrypt(
            "hello world".as_bytes(),
            nonce.as_bytes(),
            password.as_bytes(),
        );
        fs::write(&input_file, encrypted_content).unwrap();

        // Call the decrypt_file function
        let result = decrypt_file(
            input_file.clone(),
            output_file.clone(),
            password,
            nonce,
            stdout,
        );

        // Check that the function completed successfully
        assert!(result.is_ok());

        // Check that the output file was created and contains decrypted content
        let decrypted_content = fs::read(&output_file).unwrap();
        assert_eq!(decrypted_content, "hello world".as_bytes());

        // Clean up the test input and output files
        fs::remove_file(&input_file).unwrap();
        fs::remove_file(&output_file).unwrap();
    }

    #[test]
    fn sum_codes_to_file_with_test_mode_works() {
        let key_path = "key_test.txt";
        let nonce_path = "nonce_test.txt";

        // Create key and nonce files
        fs::write(key_path, "12345678123456781234567812345678").unwrap();
        fs::write(nonce_path, "123456789012").unwrap();

        let sum_codes_file = sum_codes_to_file(format!("{}:{}", key_path, nonce_path), true);
        fs::remove_file(key_path).unwrap();
        fs::remove_file(nonce_path).unwrap();
        let file_name_path = &sum_codes_file;
        let codes_opened = fs::read_to_string(&file_name_path).unwrap();
        eprintln!("{}", codes_opened);
        println!("{}", codes_opened);
        let is_pass = codes_opened.contains("12345678123456781234567812345678");
        let is_nonce = codes_opened.contains("123456789012");
        fs::remove_file(&file_name_path).unwrap();

        assert!(is_pass);
        assert!(is_nonce);
    }

    #[test]
    fn save_codes_to_file_with_test_mode_works() {
        let key = "12345678123456781234567812345678";
        let nonce = "123456789012";

        let saved_codes_file = save_codes_file(key.to_string(), nonce.to_string(), true);

        let file_name_path = &saved_codes_file;
        let codes_opened = fs::read_to_string(&file_name_path).unwrap();
        let is_pass = codes_opened.contains("12345678123456781234567812345678");
        let is_nonce = codes_opened.contains("123456789012");
        fs::remove_file(&file_name_path).unwrap();
        assert!(is_pass);
        assert!(is_nonce);
    }
    //     }
    // }
}