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
use pqcrypto_kyber::kyber1024::*;
use pqcrypto_kyber::kyber1024;
use pqcrypto_traits::kem::{Ciphertext, PublicKey, SecretKey, SharedSecret};
use aes::cipher::{BlockCipher, BlockEncrypt, BlockDecrypt, KeyInit, generic_array::GenericArray};
use sha2::Sha256;
use hmac::{Hmac, Mac};
use std::{error::Error, ffi::OsStr, fmt, fs, path::Path, path::PathBuf, result::Result, env};
use tokio::runtime;
use crate::{Keychain, File};

#[derive(Debug)]
pub enum CryptError {
    IOError,
    MessageExtractionError,
    InvalidMessageFormat,
    HexError(hex::FromHexError),
    EncapsulationError,
    DecapsulationError,
    WriteError,
    HmacVerificationError,
    HmacShortData,
    HmacKeyErr,
    HexDecodingError(String),
    UniqueFilenameFailed,
    MissingSecretKey,
    MissingPublicKey,
    MissingCiphertext,
    MissingSharedSecret,
    MissingData,
    InvalidParameters,
    PathError,
    Utf8Error,
    SigningFailed,
    SignatureVerificationFailed,
    InvalidSignatureLength,
    InvalidSignature,
}

impl fmt::Display for CryptError {
   fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
       match self {
           CryptError::IOError => write!(f, "IO error occurred"),
           CryptError::MessageExtractionError => write!(f, "Error extracting message"),
           CryptError::InvalidMessageFormat => write!(f, "Invalid message format"),
           CryptError::HexError(err) => write!(f, "Hex error: {}", err),
           CryptError::EncapsulationError => write!(f, "Encapsulation error"),
           CryptError::DecapsulationError => write!(f, "Decapsulation error"),
           CryptError::WriteError => write!(f, "Write error"),
           CryptError::HmacVerificationError => write!(f, "HMAC verification error"),
           CryptError::HmacShortData => write!(f, "Data is too short for HMAC verification"),
           CryptError::HmacKeyErr => write!(f, "HMAC can take key of any size"),
           CryptError::HexDecodingError(err) => write!(f, "Hex decoding error: {}", err),
           CryptError::UniqueFilenameFailed => write!(f, "Unique filename failed"),
           CryptError::MissingSecretKey => write!(f, "Missing secret key"),
           CryptError::MissingPublicKey => write!(f, "Missing public key"),
           CryptError::MissingCiphertext => write!(f, "Missing ciphertext"),
           CryptError::MissingSharedSecret => write!(f, "Missing shared secret"),
           CryptError::MissingData => write!(f, "Missing data"),
           CryptError::InvalidParameters => write!(f, "You provided Invalid parameters"),
           CryptError::PathError => write!(f, "The provided path does not exist!"),
           CryptError::Utf8Error => write!(f, "UTF-8 conversion error"),
           CryptError::SigningFailed => write!(f, "Signing file using falcon 1024 failed!"),
           CryptError::SignatureVerificationFailed => write!(f, "verification of signature using falcon 1024 failed!"),
           CryptError::InvalidSignature => write!(f, "Signature not valid!"),
           CryptError::InvalidSignatureLength => write!(f, "Data is too short for HMAC verification"),
       }
   }
}

impl Error for CryptError {}

impl From<hex::FromHexError> for CryptError {
    fn from(error: hex::FromHexError) -> Self {
        CryptError::HexError(error)
    }
}

pub enum KeyTypes {
    All,
    PublicKey,
    SecretKey,
    SharedSecret,
    Ciphertext,
}

impl File {
    pub async fn load(path: PathBuf, file_type: KeyTypes) -> Result<Vec<u8>, CryptError> {
        let file_content = fs::read_to_string(&path).map_err(|_| CryptError::IOError)?;
        let (start_label, end_label) = match file_type {
            KeyTypes::PublicKey => ("-----BEGIN PUBLIC KEY-----\n", "\n-----END PUBLIC KEY-----"),
            KeyTypes::SecretKey => ("-----BEGIN SECRET KEY-----\n", "\n-----END SECRET KEY-----"),
            KeyTypes::SharedSecret => ("-----BEGIN SHARED SECRET-----\n", "\n-----END SHARED SECRET-----"),
            KeyTypes::Ciphertext => ("-----BEGIN CIPHERTEXT-----\n", "\n-----END CIPHERTEXT-----"),
            KeyTypes::All => unreachable!(),
        };

        let start = file_content.find(start_label)
            .ok_or(CryptError::IOError)?;
        let end = file_content.rfind(end_label)
            .ok_or(CryptError::IOError)?;

        let content = &file_content[start + start_label.len()..end];
        hex::decode(content).map_err(CryptError::HexError)
    }
}

impl Keychain {
    pub fn new() -> Result<Self, CryptError> {
        let (pk, sk) = keypair();
        let (ss, ct) = encapsulate(&pk);
        Ok(Self {
            public_key: Some(pk),
            secret_key: Some(sk),
            shared_secret: Some(ss),
            ciphertext: Some(ct),
        })
    }
    
    pub fn new_keys(path: &str, name: &str) -> Result<Self, CryptError> {
        let (pk, sk) = keypair();
        let keys = Self {
            public_key: Some(pk),
            secret_key: Some(sk),
            shared_secret: None,
            ciphertext: None,
        };
        let rt = runtime::Runtime::new().unwrap();
        rt.block_on(async {
            keys.save_keys(path, name).await;
        });
        Ok(keys)
    }
    
    pub fn find_highest_numbered_file(dir_path: &Path, base_filename: &str, extension: &str) -> Option<PathBuf> {
        let mut highest_numbered_file: Option<(i32, PathBuf)> = None;

        if dir_path.is_dir() {
            for entry in fs::read_dir(dir_path).unwrap() {
                if let Ok(entry) = entry {
                    let path = entry.path();
                    if path.is_file() && path.extension() == Some(OsStr::new(extension)) {
                        if let Some(stem) = path.file_stem().and_then(OsStr::to_str) {
                            if stem.starts_with(base_filename) {
                                let number_part = &stem[base_filename.len()..];
                                if let Ok(number) = number_part.parse::<i32>() {
                                    if highest_numbered_file.is_none() || highest_numbered_file.as_ref().unwrap().0 < number {
                                        highest_numbered_file = Some((number, path));
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        highest_numbered_file.map(|(_, path)| path)
    }

    pub fn show(&self) -> Result<(), CryptError> {
        if let (Some(ref pk), Some(ref sk), Some(ref ss), Some(ref ct)) = (self.public_key.as_ref(), self.secret_key.as_ref(), self.shared_secret.as_ref(), self.ciphertext.as_ref()) {
            let ss2 = decapsulate(ct, sk);
            println!("Public Key: {}\n\nSecret Key: {}\n\nShared secret: {}\n\nDecapsulated shared secret: {}", hex::encode(pk.as_bytes()), hex::encode(sk.as_bytes()), hex::encode(ss.as_bytes()), hex::encode(ss2.as_bytes()));
            Ok(())
        } else {
            Err(CryptError::DecapsulationError)
        }
    }

    pub async fn save(&self, base_path: &str, title: &str) -> Result<(), CryptError> {
        let dir_path = format!("{}/{}", base_path, title);
        let dir = std::path::Path::new(&dir_path);
        if !dir.exists() {
            std::fs::create_dir_all(&dir).map_err(|_| CryptError::WriteError)?;
        }

        let public_key_path = Keychain::generate_unique_filename(&format!("{}/{}", dir_path, title), "pub");
        let secret_key_path = Keychain::generate_unique_filename(&format!("{}/{}", dir_path, title), "sec");
        let shared_secret_path = Keychain::generate_unique_filename(&format!("{}/{}", dir_path, title), "ss");
        let ciphertext_path = Keychain::generate_unique_filename(&format!("{}/{}", dir_path, title), "ct");

        fs::write(
            &public_key_path, 
            format!(
                "-----BEGIN PUBLIC KEY-----\n{}\n-----END PUBLIC KEY-----",
                hex::encode(self.public_key.as_ref().expect("Public key is missing").as_bytes())
            )
        ).map_err(|_| CryptError::WriteError)?;

        fs::write(
            &secret_key_path, 
            format!(
                "-----BEGIN SECRET KEY-----\n{}\n-----END SECRET KEY-----",
                hex::encode(self.secret_key.as_ref().expect("Secret key is missing").as_bytes())
            )
        ).map_err(|_| CryptError::WriteError)?;

        fs::write(
            &shared_secret_path, 
            format!(
                "-----BEGIN SHARED SECRET-----\n{}\n-----END SHARED SECRET-----",
                hex::encode(self.shared_secret.as_ref().expect("Shared secret is missing").as_bytes())
            )
        ).map_err(|_| CryptError::WriteError)?;

        fs::write(
            &ciphertext_path, 
            format!(
                "-----BEGIN CIPHERTEXT-----\n{}\n-----END CIPHERTEXT-----",
                hex::encode(self.ciphertext.as_ref().expect("Ciphertext is missing").as_bytes())
            )
        ).map_err(|_| CryptError::WriteError)?;

        Ok(())
    }

    pub async fn save_keys(&self, base_path: &str, title: &str) -> Result<(), CryptError> {
        let dir_path = format!("{}/{}", base_path, title);
        let dir = std::path::Path::new(&dir_path);
        if !dir.exists() {
            std::fs::create_dir_all(&dir).map_err(|_| CryptError::WriteError)?;
        }

        let public_key_path = Keychain::generate_unique_filename(&format!("{}/{}", dir_path, title), "pub");
        let secret_key_path = Keychain::generate_unique_filename(&format!("{}/{}", dir_path, title), "sec");

        fs::write(
            &public_key_path, 
            format!(
                "-----BEGIN PUBLIC KEY-----\n{}\n-----END PUBLIC KEY-----",
                hex::encode(self.public_key.as_ref().expect("Public key is missing").as_bytes())
            )
        ).map_err(|_| CryptError::WriteError)?;

        fs::write(
            &secret_key_path, 
            format!(
                "-----BEGIN SECRET KEY-----\n{}\n-----END SECRET KEY-----",
                hex::encode(self.secret_key.as_ref().expect("Secret key is missing").as_bytes())
            )
        ).map_err(|_| CryptError::WriteError)?;

        Ok(())
    }

    pub async fn save_public_key(&self, base_path: &str, title: &str) -> Result<(), CryptError> {
        let dir_path = format!("{}/{}", base_path, title);
        let dir = std::path::Path::new(&dir_path);
        if !dir.exists() {
            std::fs::create_dir_all(&dir).map_err(|_| CryptError::WriteError)?;
        }

        let public_key_path = Keychain::generate_unique_filename(&format!("{}/{}", dir_path, title), "pub");

        fs::write(
            &public_key_path, 
            format!(
                "-----BEGIN PUBLIC KEY-----\n{}\n-----END PUBLIC KEY-----",
                hex::encode(self.public_key.as_ref().expect("Public key is missing").as_bytes())
            )
        ).map_err(|_| CryptError::WriteError)?;

        Ok(())
    }

      
    pub async fn save_secret_key(&self, base_path: &str, title: &str) -> Result<(), CryptError> {
        let dir_path = format!("{}/{}", base_path, title);
        let dir = std::path::Path::new(&dir_path);
        if !dir.exists() {
            std::fs::create_dir_all(&dir).map_err(|_| CryptError::WriteError)?;
        }

        let secret_key_path = Keychain::generate_unique_filename(&format!("{}/{}", dir_path, title), "sec");

        fs::write(
            &secret_key_path, 
            format!(
                "-----BEGIN SECRET KEY-----\n{}\n-----END SECRET KEY-----",
                hex::encode(self.secret_key.as_ref().expect("Secret key is missing").as_bytes())
            )
        ).map_err(|_| CryptError::WriteError)?;

        Ok(())
    }


    pub async fn save_ciphertext(&self, base_path: &str, title: &str) -> Result<(), CryptError> {
        let dir_path = format!("{}/{}", base_path, title);
        let dir = std::path::Path::new(&dir_path);
        if !dir.exists() {
            std::fs::create_dir_all(&dir).map_err(|_| CryptError::WriteError)?;
        }

        let ciphertext_path = Keychain::generate_unique_filename(&format!("{}/{}", dir_path, title), "ct");

        let ciphertext = self.ciphertext.as_ref().expect("Ciphertext is missing");
        fs::write(
            &ciphertext_path, 
            format!(
                "-----BEGIN CIPHERTEXT-----\n{}\n-----END CIPHERTEXT-----",
                hex::encode(ciphertext.as_bytes())
            )
        ).map_err(|_| CryptError::WriteError)?;

        Ok(())
    }


    pub async fn save_shared_secret(&self, base_path: &str, title: &str) -> Result<(), CryptError> {
        let dir_path = format!("{}/{}", base_path, title);
        let dir = std::path::Path::new(&dir_path);
        if !dir.exists() {
            std::fs::create_dir_all(&dir).map_err(|_| CryptError::WriteError)?;
        }

        let shared_secret_path = Keychain::generate_unique_filename(&format!("{}/{}", dir_path, title), "ss");

        fs::write(
            &shared_secret_path, 
            format!(
                "-----BEGIN SHARED SECRET-----\n{}\n-----END SHARED SECRET-----",
                hex::encode(self.shared_secret.as_ref().expect("Shared secret is missing").as_bytes())
            )
        ).map_err(|_| CryptError::WriteError)?;

        Ok(())
    }


    pub async fn load_public_key(&mut self, path: PathBuf) -> Result<kyber1024::PublicKey, CryptError> {
        let public_key_bytes = File::load(path, KeyTypes::PublicKey).await?;
        let public_key = PublicKey::from_bytes(&public_key_bytes).unwrap();

        println!("Successfully loaded public key.\n");
        self.public_key = Some(public_key);
        Ok(public_key)
    }

    pub async fn load_secret_key(&mut self, path: PathBuf) -> Result<kyber1024::SecretKey, CryptError> {
        let secret_key_bytes = File::load(path, KeyTypes::SecretKey).await?;
        let secret_key: kyber1024::SecretKey = SecretKey::from_bytes(&secret_key_bytes).unwrap();

        println!("Successfully loaded secret key.\n");
        self.secret_key = Some(secret_key);
        Ok(secret_key)
    }

    pub async fn load_ciphertext(&mut self, path: PathBuf) -> Result<kyber1024::Ciphertext, CryptError> {
        let cipher_bytes = File::load(path, KeyTypes::Ciphertext).await?;
        let cipher: kyber1024::Ciphertext = Ciphertext::from_bytes(&cipher_bytes).unwrap();

        println!("Successfully loaded ciphertext.\n");
        self.ciphertext = Some(cipher);
        Ok(cipher)
    }

    pub async fn load_shared_secret(&mut self, path: PathBuf) -> Result<kyber1024::SharedSecret, CryptError> {
        let shared_secret_bytes = File::load(path, KeyTypes::SharedSecret).await?;
        let shared_secret: kyber1024::SharedSecret = SharedSecret::from_bytes(&shared_secret_bytes).unwrap();

        println!("Successfully loaded shared secret.\n");
        self.shared_secret = Some(shared_secret);
        Ok(shared_secret)
    }

    pub async fn get_public_key(&self) -> Result<kyber1024::PublicKey, CryptError> {
        let public = self.public_key.unwrap();
        Ok(public)
    }

    pub async fn get_secret_key(&self) -> Result<kyber1024::SecretKey, CryptError> {
        let secret = self.secret_key.unwrap();
        Ok(secret)
    }

    pub async fn get_ciphertext(&self) -> Result<kyber1024::Ciphertext, CryptError> {
        let cipher = self.ciphertext.unwrap();
        Ok(cipher)
    }

    pub async fn get_shared_secret(&self) -> Result<kyber1024::SharedSecret, CryptError> {
        let shared_sec = self.shared_secret.unwrap();
        Ok(shared_sec)
    }

    pub fn generate_unique_filename(base_path: &str, extension: &str) -> String {
        let mut counter = 1;
        let mut unique_path = format!("{}.{}", base_path, extension);
        while std::path::Path::new(&unique_path).exists() {
            unique_path = format!("{}_{}.{}", base_path, counter, extension);
            counter += 1;
        }
        unique_path
    }
}