ferric_crypto_lib 0.2.7

A library for Ferric Crypto
Documentation
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
use crate::error::CharacterParseError;
use crate::error::MixError;
use crate::prelude::{encode_string, ALPHABET_LEN};
use crate::utils::BaseString;
#[cfg(feature = "python-integration")]
use pyo3::{pyclass, PyErr};

#[derive(Debug, Default, Clone, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "python-integration", pyclass(get_all))]
pub struct MixKey {
    pub keys: Vec<Vec<usize>>,
    pub len: usize,
}

#[cfg(not(feature = "python-integration"))]
impl MixKey {
    /// Constructs a new `MixKey` instance.
    ///
    /// # Arguments
    ///
    /// * `k1` - A vector of `usize` that represents the first key.
    /// * `k2` - A vector of `usize` that represents the second key.
    /// * `k3` - A vector of `usize` that represents the third key.
    ///
    /// # Returns
    ///
    /// * `Result<Self, MixError>` - A new `Key` instance if the keys are valid, or a `MixError` if they are not.
    ///
    /// # Example
    ///
    /// ```
    /// # use ferric_crypto_lib::crypto_systems::mix::MixKey;
    /// let k1 = vec![1, 2, 3];
    /// let k2 = vec![1, 2, 3];
    /// let k3 = vec![1, 2, 3];
    /// let key = MixKey::new(k1, k2, k3).unwrap();
    /// ```
    pub fn new(k1: Vec<usize>, k2: Vec<usize>, k3: Vec<usize>) -> Result<Self, MixError> {
        let k = vec![k1.clone(), k2, k3];

        let mut key = Self {
            keys: k,
            len: 0usize,
        };

        if !key.is_valid() {
            Err(MixError::InvalidKey)
        } else {
            key.len = k1.len();
            Ok(key)
        }
    }

    pub fn new_with_len(key_len: usize) -> Self {
        let k1 = vec![0; key_len];
        let k2 = vec![0; key_len];
        let k3 = vec![0; key_len];

        Self::new(k1, k2, k3).unwrap()
    }

    /// Checks if the keys in the `Key` instance are valid.
    ///
    /// # Returns
    ///
    /// * `bool` - `true` if the keys are valid, `false` otherwise.
    ///
    /// # Validity Criteria
    ///
    /// A key is considered valid if all of its elements are less than `ALPHABET_LEN`, and all keys have the same length.
    pub fn is_valid(&self) -> bool {
        for (i, key) in self.keys.iter().enumerate() {
            for num in key.iter() {
                if *num >= *ALPHABET_LEN {
                    return false;
                }
            }
        }

        if self.keys[0].len() != self.keys[1].len() || self.keys[0].len() != self.keys[2].len() {
            return false;
        }
        true
    }
}

/// The `Mix` struct represents a symmetric cryptographic system that is a mix of three ciphers: Feistel, Hill, and Vigenère.
/// This cryptographic system was developed by Robert Nyqvist.
///
/// A plaintext block `m` in `Z^(8)28` is divided into two vectors `L0` and `R0` in `Z^(4)28`, so that `m = (L0, R0)`.
/// The ciphertext `c = (L3, R3)` is then determined recursively according to
/// `Ln = Rn-1` and `Rn = Ln-1 + f(Rn-1, Kn) (mod 28)`,
/// where `K1, K2, K3` in `Z428` are the encryption keys.
/// The function `f` is given by `f(R, K) ≡ P R + K`,
/// where `P` is a 4x4 matrix with the values `[1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1] (mod 28)`.
/// To perform the calculation `P R + K`, `R` and `K` are considered as column matrices.
///
/// # Fields
///
/// * `key` - A `Key` instance that will be used for the encryption process.
/// * `rounds` - The number of rounds to be performed in the encryption process. Currently it only supports 3 rounds but i wish to make this configurable.
///
/// # Example
///
/// ```
/// # use ferric_crypto_lib::crypto_systems::mix::{Mix, MixKey};
/// # use ferric_crypto_lib::Traits::{Encrypt, Decrypt};
/// let k1 = vec![0, 27, 27, 0];
/// let k2 = vec![1, 0, 0, 1];
/// let k3 = vec![15, 15, 15, 15];
///
/// let clear_text = "rötmånad".to_string();
/// let key = MixKey::new(k1, k2, k3).expect("Key is invalid");
/// let mix = Mix::new(key);
/// let result = mix.encrypt(clear_text);
///
/// assert_eq!(result.unwrap(), "mlbrnbpb");
/// ```
#[derive(Debug, Default)]
#[cfg_attr(feature = "python-integration", pyclass(get_all))]
pub struct Mix {
    pub key: MixKey,
    pub rounds: usize,
}

#[cfg(not(feature = "python-integration"))]
impl Mix {
    /// Constructs a new `Mix` instance.
    ///
    /// # Arguments
    ///
    /// * `key` - A `MixKey` instance that will be used for the encryption process.
    ///
    /// # Returns
    ///
    /// * A new `Mix` instance.
    ///
    /// # Example
    ///
    /// ```
    /// # use ferric_crypto_lib::crypto_systems::mix::{Mix, MixKey};
    /// let key = MixKey::new(vec![1, 2, 3], vec![1, 2, 3], vec![1, 2, 3]).unwrap();
    /// let mix = Mix::new(key);
    /// ```
    pub fn new(key: MixKey) -> Self {
        Self {
            key,
            rounds: 3usize,
        }
    }

    /// Splits the input string into chunks of equal length based on the length of the key.
    ///
    /// # Arguments
    ///
    /// * `input` - A `String` that will be split into chunks.
    ///
    /// # Returns
    ///
    /// * `Result<Vec<Vec<usize>>, MixError>` - A 2D vector of `usize` if the operation is successful, or a `MixError` if it fails.
    ///
    /// # Errors
    ///
    /// This function will return an error if the length of the input string is not a multiple of the length of the key.
    ///
    /// # Example
    ///
    /// ```
    /// # use ferric_crypto_lib::crypto_systems::mix::{Mix, MixKey};
    /// let key = MixKey::new(vec![1, 2, 3], vec![1, 2, 3], vec![1, 2, 3]).unwrap();
    /// let mix = Mix::new(key);
    /// let input = "abcdef".to_string();
    /// let result = mix.get_split_input(input).unwrap();
    /// assert_eq!(result, vec![vec![0, 1, 2], vec![3, 4, 5]]);
    /// ```
    pub fn get_split_input(&self, input: String) -> Result<Vec<Vec<usize>>, MixError> {
        if input.chars().count() % self.key.keys[0].len() != 0 {
            return Err(MixError::InvalidInput);
        }

        let input = BaseString::from(input);

        match input.encode() {
            Ok(string_vec) => Ok(string_vec
                .data
                .chunks(self.key.len)
                .map(|chunk| chunk.to_vec())
                .collect()),
            Err(e) => Err(MixError::CharacterParseError(e)),
        }
    }
}

impl From<Vec<Vec<usize>>> for Mix {
    fn from(keys: Vec<Vec<usize>>) -> Self {
        // Construct the Key from the provided Vec<Vec<usize>>
        let key = MixKey::new(keys[0].clone(), keys[1].clone(), keys[2].clone())
            .expect("Invalid keys provided");

        // Create a new Mix instance with the constructed Key
        Self {
            key,
            rounds: 3, // you can set the default rounds here
        }
    }
}

#[cfg(feature = "python-integration")]
mod python_inegration {
    use super::*;
    use crate::Traits::{Decrypt, Encrypt};
    use pyo3::{prelude::*, pymethods, PyResult};
    use std::collections::HashMap;

    #[pymethods]
    impl Mix {
        /// Constructs a new `Mix` instance.
        ///
        /// # Arguments
        ///
        /// * `key` - A `MixKey` instance that will be used for the encryption process.
        ///
        /// # Returns
        ///
        /// * A new `Mix` instance.
        ///
        /// # Example
        ///
        /// ```
        /// let key = Key::new(vec![1, 2, 3], vec![1, 2, 3], vec![1, 2, 3]).unwrap();
        /// let mix = Mix::new(key);
        /// ```
        #[new]
        pub fn new(key: MixKey) -> Self {
            Self {
                key,
                rounds: 3usize,
            }
        }

        /// Splits the input string into chunks of equal length based on the length of the key.
        ///
        /// # Arguments
        ///
        /// * `input` - A `String` that will be split into chunks.
        ///
        /// # Returns
        ///
        /// * `Result<Vec<Vec<usize>>, MixError>` - A 2D vector of `usize` if the operation is successful, or a `MixError` if it fails.
        ///
        /// # Errors
        ///
        /// This function will return an error if the length of the input string is not a multiple of the length of the key.
        ///
        /// # Example
        ///
        /// ```
        /// let key = Key::new(vec![1, 2, 3], vec![1, 2, 3], vec![1, 2, 3]).unwrap();
        /// let mix = Mix::new(key);
        /// let input = "abcdef".to_string();
        /// let result = mix.get_split_input(input).unwrap();
        /// ```
        pub fn get_split_input(&self, input: String) -> Result<Vec<Vec<usize>>, MixError> {
            if input.chars().count() % self.key.keys[0].len() != 0 {
                return Err(MixError::InvalidInput);
            }

            match encode_string(&input) {
                Ok(string_vec) => Ok(string_vec
                    .chunks(self.key.len)
                    .map(|chunk| chunk.to_vec())
                    .collect()),
                Err(e) => Err(MixError::CharacterParseError(e)),
            }
        }

        pub fn print(&self) {
            println!("{:?}", self);
        }

        pub fn encrypt(&self, input: String) -> PyResult<String> {
            match Encrypt::encrypt(self, input) {
                Ok(s) => Ok(s),
                Err(e) => Err(pyo3::exceptions::PyException::new_err(format!("{:?}", e))),
            }
        }

        pub fn decrypt(&self, input: String) -> PyResult<String> {
            match Decrypt::decrypt(self, input) {
                Ok(s) => Ok(s),
                Err(e) => Err(pyo3::exceptions::PyException::new_err(format!("{:?}", e))),
            }
        }

        #[pyo3(signature = (input="".to_string(), clear_text=None, key_info=[None, None, None]))]
        pub fn brute_force(
            &mut self,
            input: String,
            clear_text: Option<String>,
            key_info: [Option<Vec<usize>>; 3],
        ) -> PyResult<HashMap<MixKey, String>> {
            match crate::Traits::BruteForce::brute_force(self, input, clear_text, key_info) {
                Ok(s) => Ok(s),
                Err(e) => Err(pyo3::exceptions::PyException::new_err(format!("{:?}", e))),
            }
        }

        #[staticmethod]
        pub fn create_from_keys(keys: Vec<Vec<usize>>) -> PyResult<Self> {
            if keys.len() != 3 {
                return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(
                    "Expected exactly three keys",
                ));
            }

            let key = MixKey::new(keys[0].clone(), keys[1].clone(), keys[2].clone())
                .map_err(|e| PyErr::new::<pyo3::exceptions::PyValueError, _>(format!("{:?}", e)))?;

            Ok(Mix::new(key))
        }
    }

    #[pymethods]
    impl MixKey {
        /// Constructs a new `MixKey` instance.
        ///
        /// # Arguments
        ///
        /// * `k1` - A vector of `usize` that represents the first key.
        /// * `k2` - A vector of `usize` that represents the second key.
        /// * `k3` - A vector of `usize` that represents the third key.
        ///
        /// # Returns
        ///
        /// * `Result<Self, MixError>` - A new `Key` instance if the keys are valid, or a `MixError` if they are not.
        ///
        /// # Example
        ///
        /// ```
        /// let k1 = vec![1, 2, 3];
        /// let k2 = vec![1, 2, 3];
        /// let k3 = vec![1, 2, 3];
        /// let key = Key::new(k1, k2, k3).unwrap();
        /// ```
        #[new]
        pub fn new(k1: Vec<usize>, k2: Vec<usize>, k3: Vec<usize>) -> Result<Self, MixError> {
            let k = vec![k1.clone(), k2, k3];

            let mut key = Self {
                keys: k,
                len: 0usize,
            };

            if !key.is_valid() {
                Err(MixError::InvalidKey)
            } else {
                key.len = k1.len();
                Ok(key)
            }
        }

        /// Checks if the keys in the `Key` instance are valid.
        ///
        /// # Returns
        ///
        /// * `bool` - `true` if the keys are valid, `false` otherwise.
        ///
        /// # Validity Criteria
        ///
        /// A key is considered valid if all of its elements are less than `ALPHABET_LEN`,
        /// and all keys have the same length.
        pub fn is_valid(&self) -> bool {
            for (i, key) in self.keys.iter().enumerate() {
                for num in key.iter() {
                    if *num >= *ALPHABET_LEN {
                        return false;
                    }
                }
            }

            if self.keys[0].len() != self.keys[1].len() || self.keys[0].len() != self.keys[2].len()
            {
                return false;
            }
            true
        }

        pub fn print_keys(&self) {
            for key in self.keys.iter() {
                println!("{:?}", key);
            }
        }
    }
}

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

    #[test]
    fn test_from() {
        let keys = vec![vec![1, 2, 3], vec![1, 2, 3], vec![1, 2, 3]];

        let mix = Mix::from(keys);

        assert_eq!(mix.key.keys[0], vec![1, 2, 3]);
        assert_eq!(mix.key.keys[1], vec![1, 2, 3]);
        assert_eq!(mix.key.keys[2], vec![1, 2, 3]);
    }

    #[test]
    fn key_creation_with_valid_values() {
        let k1 = vec![1, 2, 3];
        let k2 = vec![1, 2, 3];
        let k3 = vec![1, 2, 3];
        let key = MixKey::new(k1, k2, k3);
        assert!(key.is_ok());
    }

    #[test]
    fn key_creation_with_invalid_values() {
        let k1 = vec![1, 2, 3];
        let k2 = vec![1, 2, 3];
        let k3 = vec![1, 2, 3, 4]; // Extra element
        let key = MixKey::new(k1, k2, k3);
        assert!(key.is_err());
    }

    #[test]
    fn key_creation_with_values_exceeding_alphabet_len() {
        let k1 = vec![*ALPHABET_LEN, 2, 3]; // First element exceeds ALPHABET_LEN
        let k2 = vec![1, 2, 3];
        let k3 = vec![1, 2, 3];
        let key = MixKey::new(k1, k2, k3);
        assert!(key.is_err());
    }

    #[test]
    fn key_validation_with_valid_values() {
        let k1 = vec![1, 2, 3];
        let k2 = vec![1, 2, 3];
        let k3 = vec![1, 2, 3];
        let key = MixKey::new(k1, k2, k3).unwrap();
        assert!(key.is_valid());
    }

    #[test]
    fn key_validation_with_invalid_values() {
        let k1 = vec![1, 2, 3];
        let k2 = vec![1, 2, 3];
        let k3 = vec![1, 2, 3, 4]; // Extra element
        let key = MixKey::new(k1, k2, k3);
        assert!(key.is_err());
    }

    #[test]
    fn key_validation_with_values_exceeding_alphabet_len() {
        let k1 = vec![*ALPHABET_LEN, 2, 3]; // First element exceeds ALPHABET_LEN
        let k2 = vec![1, 2, 3];
        let k3 = vec![1, 2, 3];
        let key = MixKey::new(k1, k2, k3);
        assert!(key.is_err());
    }

    #[test]
    fn test_get_split_input() {
        let k1 = vec![1, 2, 3];
        let k2 = vec![1, 2, 3];
        let k3 = vec![1, 2, 3];
        let key = MixKey::new(k1, k2, k3).unwrap();
        let mix = Mix::new(key);
        let input = "abcdef".to_string();
        let result = mix.get_split_input(input).unwrap();
        let expected = vec![vec![0, 1, 2], vec![3, 4, 5]];
        assert_eq!(result, expected);
    }

    use crate::crypto_systems::mix::{Mix, MixKey};
    use crate::Traits::{Decrypt, Encrypt};

    fn brute_force() -> Vec<usize> {
        let k1 = vec![13, 5, 1, 0];
        let k2 = vec![12, 4, 16, 8];

        let crypto_text = String::from("HJUMTKLC");

        for i in 0..28 {
            for j in 0..28 {
                for k in 0..28 {
                    for l in 0..28 {
                        let k3 = vec![i, j, k, l];
                        let key = match MixKey::new(k1.clone(), k2.clone(), k3.clone()) {
                            Ok(k) => k,
                            Err(e) => {
                                println!("{:?}", e);
                                continue;
                            }
                        };
                        let mix = Mix::new(key);

                        match mix.decrypt(crypto_text.clone()) {
                            Ok(s) => {
                                if s == "orosmoln" {
                                    return k3.clone();
                                }
                            }
                            Err(e) => println!("{:?}", e),
                        };
                    }
                }
            }
        }
        vec![]
    }

    #[test]
    fn test_brute_force() {
        let k1 = vec![13, 5, 1, 0];
        let k2 = vec![12, 4, 16, 8];
        let k3 = brute_force();
        let key = match MixKey::new(k1, k2, k3) {
            Ok(k) => k,
            Err(e) => {
                println!("{:?}", e);
                return;
            }
        };

        let mix = Mix::new(key);

        let input = String::from("orosmoln");

        match mix.encrypt(input) {
            Ok(s) => println!("{}", s),
            Err(e) => println!("{:?}", e),
        };

        let crypto_text = String::from("YTVRVNLR");

        match mix.decrypt(crypto_text) {
            Ok(s) => println!("{}", s),
            Err(e) => println!("{:?}", e),
        };
    }
}