crypt_ro/
lib.rs

1//! A cryptographic library providing matrix-based encryption and decryption.
2//!
3//! This library implements a custom encryption scheme using:
4//! - Matrix transformations with configurable size
5//! - Key-derived shuffling operations
6//! - Random padding and mixing operations
7//! - URL-safe base64 encoding for text operations
8//!
9//! # Features
10//! - Configurable matrix size for transformation blocks
11//! - Both raw byte and text-friendly operations
12//! - Key-based encryption/decryption
13//! - Randomized padding for better security
14//!
15//! # Examples
16//!
17//! Basic usage:
18//!
19//! ```
20//! use crypt_ro::Cryptor;
21//!
22//! let cryptor = Cryptor::new();
23//! let secret = "my secret message";
24//! let key = "strong password";
25//!
26//! // Encrypt and decrypt text
27//! let encrypted = cryptor.encrypt_text(secret, key).unwrap();
28//! let decrypted = cryptor.decrypt_text(&encrypted, key).unwrap();
29//!
30//! assert_eq!(decrypted, secret);
31//!
32//! // Using custom matrix size
33//! let mut cryptor = Cryptor::new();
34//! cryptor.set_matrix(64);  // Use larger blocks
35//! let encrypted = cryptor.encrypt_text(secret, key).unwrap();
36//! let decrypted = cryptor.decrypt_text(&encrypted, key).unwrap();
37//!
38//! assert_eq!(decrypted, secret);
39//! ```
40//!
41//! Working with raw bytes:
42//!
43//! ```
44//! use crypt_ro::Cryptor;
45//!
46//! let cryptor = Cryptor::new();
47//! let data = b"binary data \x01\x02\x03";
48//! let key = "encryption key";
49//!
50//! let encrypted = cryptor.encrypt(data, key).unwrap();
51//! let decrypted = cryptor.decrypt(&encrypted, key).unwrap();
52//!
53//! assert_eq!(decrypted.as_bytes(), data);
54//! ```
55
56mod util;
57
58use base64::{engine::general_purpose::URL_SAFE, Engine as _};
59use std::error::Error;
60use crate::util::{generate_password, get_random_bytes, mix, shuffle, unmix, unshuffle};
61
62/// A cryptographic utility for encrypting and decrypting text using a matrix-based transformation.
63///
64/// The `Cryptor` uses a combination of shuffling, mixing, and matrix operations to obscure the
65/// original text. It supports configurable matrix sizes for the transformation process.
66///
67/// # Examples
68///
69/// ```
70/// use crypt_ro::Cryptor;
71///
72/// let cryptor = Cryptor::new();
73/// let encrypted = cryptor.encrypt_text("secret message", "password").unwrap();
74/// let decrypted = cryptor.decrypt_text(&encrypted, "password").unwrap();
75/// assert_eq!(decrypted, "secret message");
76/// ```
77pub struct Cryptor {
78    matrix: usize,
79}
80const RANDOM_LEN: usize = 3;
81impl Cryptor {
82    /// Creates a new `Cryptor` instance with default matrix size (32).
83    pub fn new() -> Self {
84        Self { matrix: 32 }
85    }
86
87    /// Encrypts raw bytes using the provided key.
88    ///
89    /// # Arguments
90    /// * `data` - The bytes to encrypt
91    /// * `key` - The encryption key
92    ///
93    /// # Returns
94    /// A `Result` containing the encrypted bytes or an error if encryption fails.
95    ///
96    /// # Example
97    /// ```
98    /// use crypt_ro::Cryptor;
99    ///
100    /// let cryptor = Cryptor::new();
101    /// let encrypted = cryptor.encrypt(b"secret data", "key123").unwrap();
102    /// assert!(!encrypted.is_empty());
103    /// ```
104    pub fn encrypt(&self, data: &[u8], key: &str) -> Result<Vec<u8>, Box<dyn Error>> {
105        let matrix_size=self.matrix;
106        let key_bytes = generate_password(matrix_size,key.as_bytes());
107        let data_size = (data.len() as u32).to_be_bytes();
108        let random_prefix = get_random_bytes(6);
109        let seed_random = random_prefix.iter().map(|&b| b as u16).sum::<u16>() as u64;
110        let mut padded_text = Vec::with_capacity(10 + data.len());
111        padded_text.extend_from_slice(&data_size);
112        padded_text.extend_from_slice(&random_prefix);
113        padded_text.extend_from_slice(data);
114
115        let seed_sum: u64 = key_bytes.iter().map(|&b| b as u64).sum();
116        shuffle(&mut padded_text,seed_sum.wrapping_add(seed_random),5);
117
118        let mut matrix = padded_text.chunks_exact_mut(matrix_size).collect::<Vec<_>>();
119        let matrix_len=matrix.len();
120
121        for i in 0..matrix_len {
122            let seed = matrix.get(i+1)
123                .map(|b| b[0] as u64)
124                .unwrap_or(key_bytes[0] as u64);
125            shuffle(&mut matrix[i], seed.wrapping_add(seed_random),2);
126        }
127
128        mix(matrix_size,&mut padded_text, &key_bytes);
129        let seed_random=(seed_random as u16).to_be_bytes();
130        padded_text.push(seed_random[0]);
131        padded_text.push(seed_random[1]);
132        Ok(padded_text)
133    }
134
135
136    /// Encrypts raw bytes using the provided key.
137    ///
138    /// # Arguments
139    /// * `text` - The plaintext to encrypt
140    /// * `key` - The encryption key
141    ///
142    /// # Returns
143    /// A `Result` URL-safe base64 string without padding or an error if encryption fails.
144    ///
145    /// # Example
146    /// ```
147    /// use crypt_ro::Cryptor;
148    ///
149    /// let cryptor = Cryptor::new();
150    /// let encrypted = cryptor.encrypt_text("secret message", "password").unwrap();
151    /// assert!(!encrypted.contains('/'));  // URL-safe
152    pub fn encrypt_text(&self, text: &str, key: &str) -> Result<String, Box<dyn Error>> {
153        Ok(URL_SAFE.encode(self.encrypt(text.as_bytes(), key)?).trim_end_matches('=').to_string())
154    }
155
156    /// Decrypts bytes using the provided key.
157    ///
158    /// # Arguments
159    /// * `encoded` - The encrypted bytes to decrypt
160    /// * `key` - The decryption key
161    ///
162    /// # Returns
163    /// A `Result` containing the decrypted bytes or an error if decryption fails.
164    ///
165    /// # Example
166    /// ```
167    /// use crypt_ro::Cryptor;
168    ///
169    /// let cryptor = Cryptor::new();
170    /// let encrypted = cryptor.encrypt(b"data", "key").unwrap();
171    /// let decrypted = cryptor.decrypt(&encrypted, "key").unwrap();
172    /// assert_eq!(decrypted, b"data");
173    /// ```
174    pub fn decrypt(&self, encoded: &Vec<u8>, key: &str) -> Result<Vec<u8>, Box<dyn Error>> {
175        let len=encoded.len();
176        if len < 6 {
177            return Err("Invalid Token Matrix Length".into());
178        }
179
180        let seed_random=u16::from_be_bytes([encoded[len - 2],encoded[len - 1]]) as u64;
181        let mut decoded = encoded[..len-2].to_vec();
182        let len=len-2;
183        let matrix_size=self.matrix;
184
185        let key_bytes = generate_password(matrix_size,key.as_bytes());
186        unmix(matrix_size,&mut decoded, &key_bytes);
187        let mut matrix = decoded.chunks_exact_mut(matrix_size).collect::<Vec<_>>();
188        let matrix_len=matrix.len();
189        for i in (0..matrix_len).rev() {
190            let seed = matrix.get(i+1)
191                .map(|b| b[0] as u64)
192                .unwrap_or(key_bytes[0] as u64);
193            unshuffle(&mut matrix[i], seed.wrapping_add(seed_random),2);
194        }
195
196
197        let seed_sum: u64 = key_bytes.iter().map(|&b| b as u64).sum();
198        unshuffle(&mut decoded, seed_sum.wrapping_add(seed_random),5);
199
200        let data_size = u32::from_be_bytes([decoded[0], decoded[1], decoded[2], decoded[3]]) as usize;
201        if len < data_size+10 {
202            return Err("Invalid Token Matrix Length".into());
203        }
204        let result_bytes = &decoded[10..data_size+10];
205        Ok(result_bytes.to_vec())
206    }
207
208    /// Decrypts a URL-safe base64 encoded string using the provided key.
209    ///
210    /// # Arguments
211    /// * `encoded` - A URL-safe base64 encoded string to decrypt
212    /// * `key` - The decryption key
213    ///
214    /// # Returns
215    /// A `Result` containing the decrypted string or an error if decryption fails.
216    ///
217    /// # Example
218    /// ```
219    /// use crypt_ro::Cryptor;
220    ///
221    /// let cryptor = Cryptor::new();
222    /// let encrypted = cryptor.encrypt_text("message", "pass").unwrap();
223    /// let decrypted = cryptor.decrypt_text(&encrypted, "pass").unwrap();
224    /// assert_eq!(decrypted, "message");
225    /// ```
226    pub fn decrypt_text(&self, encoded: &str, key: &str) -> Result<String, Box<dyn Error>> {
227        let mut input = encoded.to_string();
228        let padding = input.len() % 4;
229        if padding != 0 {
230            input.push_str(&"=".repeat(4 - padding));
231        }
232
233        let data = URL_SAFE.decode(&input)?;
234        let result = String::from_utf8(self.decrypt(&data, &key)?)?
235            .to_string();
236        Ok(result)
237    }
238
239    /// Sets the matrix size used for cryptographic operations.
240    ///
241    /// The matrix size determines how data is chunked and processed during encryption/decryption.
242    /// Must be a positive non-zero value.
243    ///
244    /// # Example
245    /// ```
246    /// use crypt_ro::Cryptor;
247    ///
248    /// let mut cryptor = Cryptor::new();
249    /// cryptor.set_matrix(64);  // Use larger blocks
250    /// ```
251    pub fn set_matrix(&mut self, size: usize) {
252        if size>0{
253            self.matrix = size;
254        }
255    }
256}