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
mod keychain;
mod decrypt;
mod encrypt;
mod file_remover;

#[cfg(feature = "default")]
mod sign_falcon;

#[cfg(feature = "dilithium")]
mod sign_dilithium;

use crate::{
    keychain::*,
    encrypt::*,
    decrypt::*,
    file_remover::*,
};
pub use crate::sign_falcon::Sign;
use std::{
    error::Error,
    fmt::{self, Display, Formatter},
    fs,
    path::{Path, PathBuf},
};
use tokio::io;
use pqcrypto_traits::sign::{SignedMessage as SignedMessageSign, SecretKey as SecretKeySign, PublicKey as PublicKeySign, DetachedSignature as DetachedSignatureSign};
use hex;
use pqcrypto_kyber::kyber1024;
use indicatif::{ProgressBar, ProgressStyle};
#[cfg(feature="dilithium")]
pub use crate::sign_dilithium::SignDilithium;
#[cfg(feature="dilithium")]
pub use pqcrypto_dilithium;


#[derive(Debug)]
pub enum SigningErr {
    SecretKeyMissing,
    PublicKeyMissing,
    SignatureVerificationFailed,
    SigningMessageFailed,
    IOError(io::Error),
}

impl Display for SigningErr {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            SigningErr::SecretKeyMissing => write!(f, "Secret key is missing"),
            SigningErr::PublicKeyMissing => write!(f, "Public key is missing"),
            SigningErr::SignatureVerificationFailed => write!(f, "Signature verification failed"),
            SigningErr::SigningMessageFailed => write!(f, "Failed to sign message"),
            SigningErr::IOError(err) => write!(f, "IOError occurred: {}", err),
        }
    }
}

impl PartialEq for SigningErr {
    fn eq(&self, other: &Self) -> bool {
        use SigningErr::*;
        match (self, other) {
            (SecretKeyMissing, SecretKeyMissing)
            | (PublicKeyMissing, PublicKeyMissing)
            | (SignatureVerificationFailed, SignatureVerificationFailed)
            | (SigningMessageFailed, SigningMessageFailed) => true,
            (IOError(_), IOError(_)) => false,
            _ => false,
        }
    }
}

impl From<pqcrypto_traits::Error> for SigningErr {
    fn from(_: pqcrypto_traits::Error) -> Self {
        SigningErr::SignatureVerificationFailed
    }
}

impl Error for SigningErr {}

impl From<io::Error> for SigningErr {
    fn from(err: io::Error) -> Self {
        SigningErr::IOError(err)
    }
}

pub struct Encrypt;
pub struct Decrypt;
pub struct Keychain {
    pub public_key: Option<kyber1024::PublicKey>,
    pub secret_key: Option<kyber1024::SecretKey>,
    pub shared_secret: Option<kyber1024::SharedSecret>,
    pub ciphertext: Option<kyber1024::Ciphertext>,
}
pub struct FileRemover {
    pub overwrite_times: u32,
    pub file_path: PathBuf,
    pub recursive: bool,
    pub progress_bar: ProgressBar,
}
pub struct File {
    pub path: String,
    pub data: Vec<u8>,
}

enum ActionType {
    FileAction,
    MessageAction,
}

#[cfg(test)]
mod tests {
    extern crate tempfile;
    use super::*;
        
    use crate::{
        keychain::*,
        encrypt::*,
        decrypt::*,
        file_remover::*,
        SigningErr::{*, self},
        Encrypt,
        Decrypt,
        Keychain,
        FileRemover,
        sign_falcon::*,
        ActionType,
    };
    use std::{
        path::{PathBuf, Path},
        fs,
        env::current_dir,
        io::Write,
        ffi::OsStr
    };
    use pqcrypto_kyber::kyber1024::*;
    use pqcrypto_falcon::falcon1024;
    use pqcrypto_traits::kem::{SharedSecret as SharedSecretTrait, SecretKey as SecretKeyTrait};
    use hex;
    use tempfile::{NamedTempFile, tempdir};
    use pqcrypto_traits::sign::{SignedMessage as SignedMessageSign, SecretKey as SecretKeySign, PublicKey as PublicKeySign, DetachedSignature as DetachedSignatureSign};
    #[cfg(feature = "dilithium")]
    use crate::sign_dilithium;
    #[cfg(feature = "dilithium")]
    use crate::sign_dilithium::SignDilithium; 
    #[tokio::test]
    async fn keychain_new_works() {
        let keychain = Keychain::new().unwrap();

        assert!(keychain.public_key.is_some());
        assert!(keychain.secret_key.is_some());
        assert!(keychain.shared_secret.is_some());
        assert!(keychain.ciphertext.is_some());

        if let (Some(ct), Some(sk)) = (&keychain.ciphertext, &keychain.secret_key) {
            let ss = decapsulate(ct, sk);
            assert_eq!(keychain.shared_secret.as_ref().unwrap().as_bytes(), ss.as_bytes());
        }
    }

    #[tokio::test]
    async fn generate_unique_filename_works() {
        let base_path = "test_file";
        let extension = "txt";
        let unique_path = Keychain::generate_unique_filename(base_path, extension);

        // Create a file at the unique path for the test
        fs::write(&unique_path, "Test content").unwrap();

        assert!(Path::new(&unique_path).is_file());

        assert_eq!(Path::new(&unique_path).extension().unwrap().to_str().unwrap(), extension);

        // Cleanup
        fs::remove_file(unique_path).unwrap();
    }


    #[tokio::test]
    async fn generate_original_filename_works() {
        let encrypt_filename1 = "./test_file.txt_1.enc";
        let encrypt_filename2 = "./test_file.txt.enc";
        let decrypt: Decrypt = Decrypt::new();
        let encrypt: Encrypt = Encrypt::new();
        let original1 = decrypt.generate_original_filename(encrypt_filename1).await;
        let original2 = decrypt.generate_original_filename(encrypt_filename2).await;
        assert_eq!("./test_file.txt", original1);
        assert_eq!("./test_file.txt", original2);
    }


    #[tokio::test]
    async fn generate_and_verify_hmac() {
        let decrypt: Decrypt = Decrypt::new();
        let encrypt: Encrypt = Encrypt::new();
        let key = b"Hello, how are you?";
        let data = b"Ax23526";

        // Generate HMAC
        let hmac = Encrypt::generate_hmac(key, data);

        // Prepare data for verification (append hmac to original data)
        let data_with_hmac = [data.as_ref(), hmac.as_ref()].concat();

        // Verify HMAC
        let hmac_len = 64; // Length of HMAC (depends on the hash function used, SHA512 produces 64 bytes)
        let verification_result = decrypt.verify_hmac(key, &data_with_hmac, hmac_len);

        // Assertions
        assert!(verification_result.is_ok(), "HMAC verification failed");
        let verified_data = verification_result.unwrap();
        assert_eq!(verified_data, data, "Verified data does not match original data");
    }

    #[tokio::test]
    async fn test_encrypt_decrypt_file() {
        let decrypt: Decrypt = Decrypt::new();
        let encrypt: Encrypt = Encrypt::new();
        let keychain = Keychain::new().unwrap();

        // Setup - create a sample message
        let message = "This is a test message.";
        let message_bytes = message.as_bytes();

        // Create temporary directory for test files
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("test_message.txt");
        let encrypted_file_path = dir.path().join("test_message_encrypted.txt");
        let decrypted_file_path = dir.path().join("test_message_decrypted.txt");

        fs::write(&file_path, message_bytes).expect("Failed to write test file");

        // Encrypt the file
        let encrypted_data = encrypt.encrypt_file(
            file_path.clone(), 
            keychain.shared_secret.as_ref().unwrap(), 
            b"hmackey"
        ).await.expect("Encryption failed");

        // Verify that encrypted data is different
        assert_ne!(message_bytes, encrypted_data);

        // Write encrypted data to file
        fs::write(&encrypted_file_path, &encrypted_data).expect("Failed to write encrypted file");

        // Decrypt the file
        let decrypted_data = decrypt.decrypt_file(
            &encrypted_file_path, 
            keychain.shared_secret.as_ref().unwrap(), 
            b"hmackey"
        ).await.expect("Decryption failed");

        // Write decrypted data to file
        fs::write(&decrypted_file_path, &decrypted_data).expect("Failed to write decrypted file");

        // Verify that decrypted data matches original message
        assert_eq!(message_bytes, decrypted_data);

        // Clean up - remove temporary files and directory
        dir.close().unwrap();
    }

    #[tokio::test]
    async fn test_encrypt_decrypt_message() {
        let decrypt: Decrypt = Decrypt::new();
        let encrypt: Encrypt = Encrypt::new();
        let message = "This is a secret message!";
        let hmac_key = b"encryption_test_key";

        // Initialize Keychain
        let keychain = Keychain::new().unwrap();

        // Encrypt the message
        let encrypted_message = encrypt.encrypt_msg(message, keychain.shared_secret.as_ref().unwrap(), hmac_key)
            .await
            .expect("Failed to encrypt message");

        // Decrypt the message
        let decrypted_message_result = decrypt.decrypt_msg(&encrypted_message, keychain.shared_secret.as_ref().unwrap(), hmac_key, false)
            .await;

        // Assert that the decrypted message matches the original message
        assert_eq!(decrypted_message_result.unwrap(), message, "Decrypted message does not match the original message");
    }

    #[tokio::test]
    async fn test_encrypt_decrypt() {
        let keychain = Keychain::new().unwrap();
        let decrypt: Decrypt = Decrypt::new();
        let encrypt: Encrypt = Encrypt::new();
        let pubkey = PathBuf::from("./keychain/key/key.pub");
        let secret_key = PathBuf::from("./keychain/key/key.sec");
        let ciphertext = PathBuf::from("./keychain/cipher/cipher.ct");

        // Create temporary directory for test files
        let dir = tempdir().unwrap();
        let original_file_path = dir.path().join("test.txt");
        let encrypted_file_path = dir.path().join("test.txt.enc");

        // Create a sample file with content to encrypt
        let original_file_contents = "this is a test file";
        fs::write(&original_file_path, original_file_contents).expect("Failed to write original file");

        // Encrypt the file
        let _ = encrypt.encrypt(pubkey, &original_file_path.as_os_str().to_str().unwrap(), ActionType::FileAction, b"secret", None).await;

        // Decrypt the file
        let _ = decrypt.decrypt(secret_key, ciphertext, encrypted_file_path.as_os_str().to_str().unwrap(), ActionType::FileAction, b"secret", None).await;

        // Read decrypted file contents
        let decrypted_file_contents = fs::read_to_string(&original_file_path).expect("Failed to read decrypted file");

        // Verify that decrypted content matches the original content
        assert_eq!(decrypted_file_contents, original_file_contents);

        // Clean up - remove temporary files and directory
        dir.close().unwrap();
        fs::remove_file("./keychain/cipher/cipher.ct");
    }

   #[tokio::test]
    async fn test_file_removal() -> Result<(), Box<dyn std::error::Error>> {
        let keychain = Keychain::new().unwrap();
        //keychain.save("./keychain", "key").await?;

        let keychain_path = PathBuf::from("./keychain/sign");
        let duplicated_path = PathBuf::from("./key_duplicate");

        // Duplicate the directory
        fs::create_dir_all(&duplicated_path)?; // Create the target directory
        for entry in fs::read_dir(&keychain_path)? {
            let entry = entry?;
            let dest_path = duplicated_path.join(entry.file_name());
            fs::copy(entry.path(), dest_path)?;
        }

        // Use FileRemover on the duplicated directory
        match FileRemover::new(5, duplicated_path.clone(), true) {
            Ok(mut file_remover) => {
                if let Err(e) = file_remover.delete() {
                    eprintln!("Error while deleting file: {}", e);
                } else {
                    println!("File successfully deleted.");
                }
            }
            Err(e) => eprintln!("Failed to initialize file remover: {}", e),
        }

        // Check that the duplicated folder does not exist anymore
        assert!(!duplicated_path.exists(), "The duplicated folder still exists after deletion");

        Ok(())
    }
    #[tokio::test]
    async fn test_sign_msg() {
        let mut sign = Sign::new().unwrap();
        let message = b"Test message";
        let result = sign.sign_msg(message).await;
        println!("{:?}", result);
        assert!(result.is_ok());
        assert!(!result.unwrap().is_empty());
    }

    #[tokio::test]
    async fn test_signing_detached() {
        let mut sign = Sign::new().unwrap();
        let message = b"Test message";
        let result = sign.signing_detached(message).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_verify_msg() {
        let mut sign = Sign::new().unwrap();
        let message = b"Test message";
        sign.sign_msg(message).await.unwrap();
        let result = sign.verify_msg(message).await;
        println!("{:?}", result);
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_verify_detached() {
        let mut sign = Sign::new().unwrap();
        let message = b"Test message";
        let detached_signature = sign.signing_detached(message).await.unwrap();
        let result = sign.verify_detached(message).await;
        println!("{:?}", result);
        assert_eq!(result, Ok(true));
    }


    #[tokio::test]
    async fn test_sign_file() {
        // Initialize Signature struct
        let mut sign = Sign::new().unwrap();
        let _ = sign.save_keys("keychain", "sign").await;

        // Perform the sign_file operation
        let file_path = PathBuf::from("./README.md");
        let sign_result = sign.sign_file(file_path.clone()).await;
        assert!(sign_result.is_ok(), "Signing the file failed");

        // Reading the file content for verification
        let file_content = fs::read(&file_path).expect("Failed to read the file");
        
        // Verify the signature
        let verify_result = sign.verify_detached(&file_content).await;
        assert!(verify_result.is_ok(), "Signature verification failed");
        assert_eq!(verify_result.unwrap(), true, "The file signature verification failed");
    }

    #[tokio::test]
    async fn test_key_validation() {
        let mut sign = Sign::new().unwrap();
        let message = b"Test message for key validation";

        // Sign a message
        let signature = sign.signing_detached(message).await.expect("Signing failed");

        // Verify the signature using the same Sign object (which should contain the correct public key)
        let verification_result = sign.verify_detached(message).await.expect("Verification failed");

        assert!(verification_result, "Signature verification failed with the original key pair");
    }

    #[tokio::test]
    #[cfg(feature = "dilithium")]
    async fn test_sign_msg_dilithium() {
        let mut sign = SignDilithium::new().unwrap();
        let message = b"Test message";
        let result = sign.sign_msg(message).await;
        println!("{:?}", result);
        assert!(result.is_ok());
        assert!(!result.unwrap().is_empty());
    }

    #[tokio::test]
    #[cfg(feature = "dilithium")]
    async fn test_signing_detached_dilithium() {
        let mut sign = SignDilithium::new().unwrap();
        let message = b"Test message";
        let result = sign.signing_detached(message).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    #[cfg(feature = "dilithium")]
    async fn test_verify_msg_dilithium() {
        let mut sign = SignDilithium::new().unwrap();
        let message = b"Test message";
        sign.sign_msg(message).await.unwrap();
        let result = sign.verify_msg(message).await;
        println!("{:?}", result);
        assert!(result.is_ok());
    }

    #[tokio::test]
    #[cfg(feature = "dilithium")]
    async fn test_verify_detached_dilithium() {
        let mut sign = SignDilithium::new().unwrap();
        let message = b"Test message";
        let detached_signature = sign.signing_detached(message).await.unwrap();
        let result = sign.verify_detached(message).await;
        println!("{:?}", result);
        assert_eq!(result, Ok(true));
    }

    #[tokio::test]
    #[cfg(feature = "dilithium")]
    async fn test_sign_file_dilithium() {
        // Initialize Signature struct
        let mut sign = SignDilithium::new().unwrap();
        let _ = sign.save_keys("keychain", "sign");

        // Perform the sign_file operation
        let file_path = PathBuf::from("./README.md");
        let sign_result = sign.sign_file(file_path.clone()).await;
        assert!(sign_result.is_ok(), "Signing the file failed");

        // Reading the file content for verification
        let file_content = fs::read(&file_path).expect("Failed to read the file");
        
        // Verify the signature
        let verify_result = sign.verify_detached(&file_content).await;
        assert!(verify_result.is_ok(), "Signature verification failed");
        assert_eq!(verify_result.unwrap(), true, "The file signature verification failed");
    }

    #[tokio::test]
    #[cfg(feature = "dilithium")]
    async fn test_key_validation_dilithium() {
        let mut sign = SignDilithium::new().unwrap();
        let message = b"Test message for key validation";

        // Sign a message
        let signature = sign.signing_detached(message).await.expect("Signing failed");

        // Verify the signature using the same Sign object (which should contain the correct public key)
        let verification_result = sign.verify_detached(message).await.expect("Verification failed");

        assert!(verification_result, "Signature verification failed with the original key pair");
    }

    #[tokio::test]
    async fn test_append_extract_verify_signature() {
        let keychain = Keychain::new().expect("Failed to create keychain");
        let sign = Sign::new().unwrap();
        let encrypt = Encrypt::new();
        let decrypt = Decrypt::new();
        let message = "Test message";

        // Retrieve the secret key from the keychain
        let secret_key = sign.secret_key().await.unwrap();
        let public_key = sign.public_key().await;

        // Create a test message and encrypt it
        let encrypted_message = encrypt.encrypt_msg(&message, &keychain.get_shared_secret().await.unwrap(), b"hmackey")
            .await
            .expect("Encryption failed");

        // Append signature
        let signature = Encrypt::generate_signature(&encrypted_message, *secret_key);
        let signed_data = Encrypt::append_signature(&encrypted_message, signature.clone())
            .expect("Failed to append signature");

        // Extract and verify signature
        let (extracted_data, extracted_signature) = Decrypt::extract_signature(&signed_data).unwrap();


        // Verify signature validity
        let is_signature_valid = decrypt.verify_signature(extracted_signature, encrypted_message.as_slice(), &public_key.unwrap()).expect("Verification failed");
        assert!(is_signature_valid, "Signature verification failed");

        let decrypted_data = decrypt.decrypt_msg(&extracted_data, keychain.shared_secret.as_ref().unwrap(), b"hmackey", false).await.unwrap();
        assert_eq!(message, decrypted_data, "Original message does not match decrypted message!");

        // Verify the extracted data is the same as the original encrypted message
        assert_eq!(encrypted_message, extracted_data, "Original data does not match extracted data");

        // Verify the extracted signature is the same as the original signature
        assert_eq!(&signature, DetachedSignatureSign::as_bytes(&extracted_signature), "Original signature does not match extracted signature");
    }

    #[tokio::test]
    #[cfg(feature = "xchacha20")]
    async fn test_encrypt_decrypt_message_xchacha() {
        let keychain = Keychain::new().expect("Failed to create keychain");
        let encrypt = Encrypt::new();
        let decrypt = Decrypt::new();

        // Use the shared secret from Keychain
        let shared_secret = keychain.get_shared_secret().await.expect("Failed to get shared secret");
        let nonce = generate_nonce(); // Generate a nonce for xchacha20

        let message = "This is a secret message!";

        // Encrypt the message
        let encrypted_message = encrypt.encrypt_msg_xchacha20(message, &shared_secret, &nonce, "encryption_test_key".as_bytes())
            .await
            .expect("Failed to encrypt message");

        // Decrypt the message
        let decrypted_message = decrypt.decrypt_msg_xchacha20(&encrypted_message, &shared_secret, &nonce, "encryption_test_key".as_bytes(), false)
            .await
            .expect("Failed to decrypt message");

        // Verify that the decrypted message matches the original message
        assert_eq!(message, decrypted_message);
    }


    #[tokio::test]
    #[cfg(feature = "xchacha20")]
    async fn test_encrypt_decrypt_data_xchacha20() {
        let keychain = Keychain::new().expect("Failed to create keychain");
        let encrypt = Encrypt::new();
        let decrypt = Decrypt::new();
        let key = keychain.get_shared_secret().await.expect("Failed to get shared secret").as_bytes().to_owned(); // Example key
        let hmac_key = "encryption_test_key".as_bytes();
        let data = b"Example plaintext data";
        let nonce = generate_nonce(); // Generate a nonce

        println!("Original Data: {:?}", data);

        // Encrypt the data
        let encrypted_data = encrypt.encrypt_data_xchacha20(data.as_ref(), &key, &nonce, &hmac_key)
            .await
            .expect("Encryption failed");
        println!("Encrypted Data: {:?}", encrypted_data);

        // Verify HMAC
        let hmac_len = 64; // Length of HMAC (depends on the hash function used, SHA512 produces 64 bytes)
        match decrypt.verify_hmac(&hmac_key, &encrypted_data, hmac_len) {
            Ok(data_with_hmac) => {
                // Decrypt the data
                let decrypted_data = decrypt.decrypt_data_xchacha20(&data_with_hmac, &nonce, &key)
                    .await
                    .expect("Decryption failed");
                println!("Decrypted Data: {:?}", decrypted_data);

                // Assert that the decrypted data matches the original data
                assert_eq!(data, &decrypted_data[..]);
            },
            Err(e) => panic!("HMAC verification failed: {}", e),
        }
    }

    #[tokio::test]
    #[cfg(feature = "xchacha20")]
    async fn test_encrypt_decrypt_file_xchacha20() {
        let decrypt: Decrypt = Decrypt::new();
        let encrypt: Encrypt = Encrypt::new();
        let keychain = Keychain::new().unwrap();
        let nonce = generate_nonce(); // Generate a nonce

        // Setup - create a sample message
        let message = "This is a test message.";
        let message_bytes = message.as_bytes();

        // Create temporary directory for test files
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("test_message.txt");
        let encrypted_file_path = dir.path().join("test_message_encrypted.txt");
        let decrypted_file_path = dir.path().join("test_message_decrypted.txt");

        fs::write(&file_path, message_bytes).expect("Failed to write test file");

        // Encrypt the file
        let encrypted_data = encrypt.encrypt_file_xchacha20(file_path.clone(), &keychain.get_shared_secret().await.unwrap(), &nonce, b"hmackeyaergfdgrfgswgs<edgsf")
            .await
            .expect("Encryption failed");

        assert_ne!(message_bytes, encrypted_data);

        fs::write(&encrypted_file_path, &encrypted_data).expect("Failed to write encrypted file");

        // Decrypt the file
        let decrypted_data = decrypt.decrypt_file_xchacha20(&encrypted_file_path, &keychain.get_shared_secret().await.unwrap(), &nonce, b"hmackeyaergfdgrfgswgs<edgsf")
            .await
            .expect("Decryption failed");

        // Verify that decrypted data matches original content
        assert_eq!(message.as_bytes().to_vec(), decrypted_data, "Decrypted data does not match original content");
    }

    #[tokio::test]
    #[cfg(feature = "xchacha20")]
    async fn test_encrypt_decrypt_msg_xchacha20() {
        let decrypt: Decrypt = Decrypt::new();
        let encrypt: Encrypt = Encrypt::new();
        let keychain = Keychain::new().unwrap();
        let nonce = generate_nonce(); // Generate a nonce

        // Setup - create a sample message
        let message = "This is a test message.";

        // Encrypt the file
        let encrypted_data = encrypt.encrypt_msg_xchacha20(message.as_ref(), &keychain.get_shared_secret().await.unwrap(), &nonce, b"hmackeyaergfdgrfgswgs<edgsf")
            .await
            .expect("Encryption failed");

        assert_ne!(message.as_bytes(), encrypted_data);

        // Decrypt the file
        let decrypted_data = decrypt.decrypt_msg_xchacha20(&encrypted_data, &keychain.get_shared_secret().await.unwrap(), &nonce, b"hmackeyaergfdgrfgswgs<edgsf", false)
            .await
            .expect("Decryption failed");

        // Verify that decrypted data matches original content
        assert_eq!(message, decrypted_data, "Decrypted data does not match original content");
    }

    #[tokio::test]
    #[cfg(feature = "xchacha20")]
    async fn test_encrypt_decrypt_xchacha20() {
        let nonce = generate_nonce(); // Generate a nonce
        let keychain = Keychain::new().unwrap();
        let decrypt: Decrypt = Decrypt::new();
        let encrypt: Encrypt = Encrypt::new();
        let pubkey = PathBuf::from("./keychain/key/key.pub");
        let secret_key = PathBuf::from("./keychain/key/key.sec");
        let ciphertext = PathBuf::from("./keychain/cipher/cipher.ct");

        // Create temporary directory for test files
        let dir = tempdir().unwrap();
        let original_file_path = dir.path().join("test.txt");
        let encrypted_file_path = dir.path().join("test.txt.enc");

        // Create a sample file with content to encrypt
        let original_file_contents = "this is a test file";
        fs::write(&original_file_path, original_file_contents).expect("Failed to write original file");

        // Encrypt the file
        let _ = encrypt.encrypt(pubkey, &original_file_path.as_os_str().to_str().unwrap(), ActionType::FileAction, b"secret", Some(&nonce)).await;

        // Decrypt the file
        let _ = decrypt.decrypt(secret_key, ciphertext, encrypted_file_path.as_os_str().to_str().unwrap(), ActionType::FileAction, b"secret", Some(&nonce)).await;

        // Read decrypted file contents
        let decrypted_file_contents = fs::read_to_string(&original_file_path).expect("Failed to read decrypted file");

        // Verify that decrypted content matches the original content
        assert_eq!(decrypted_file_contents, original_file_contents);

        // Clean up - remove temporary files and directory
        dir.close().unwrap();
        fs::remove_file("./keychain/cipher/cipher.ct");
    }
}