1pub mod core;
6
7pub use core::{CipherElement, VigenereCipher};
8
9pub use nonempty_tools::{NonEmptySliceRef, NonEmptyVec};
10
11#[derive(Debug, Clone, PartialEq)]
15pub struct CharElement {
16 value: char,
17 index: usize,
18}
19
20impl CharElement {
21 pub fn new(value: char, index: usize) -> Self {
23 Self { value, index }
24 }
25}
26
27impl CipherElement for CharElement {
28 type Value = char;
29
30 fn index(&self) -> usize {
31 self.index
32 }
33
34 fn value(&self) -> Self::Value {
35 self.value
36 }
37}
38
39#[derive(Debug, Clone, PartialEq)]
41pub struct DigitElement {
42 value: u8, }
44
45impl DigitElement {
46 pub fn new(value: u8) -> Option<Self> {
54 if value < 10 {
55 Some(Self { value })
56 } else {
57 None
58 }
59 }
60
61 pub fn to_char(&self) -> char {
63 char::from_digit(self.value as u32, 10).unwrap()
64 }
65}
66
67impl CipherElement for DigitElement {
68 type Value = u8;
69
70 fn index(&self) -> usize {
71 self.value as usize
72 }
73
74 fn value(&self) -> Self::Value {
75 self.value
76 }
77}
78
79pub struct StringCipher {
85 charset: Vec<CharElement>,
86 modulus: usize,
87}
88
89impl StringCipher {
90 pub fn new(charset: &str) -> Result<Self, String> {
102 if charset.is_empty() {
103 return Err("字符集不能为空".to_string());
104 }
105
106 let chars: Vec<char> = charset.chars().collect();
107
108 let unique: std::collections::HashSet<_> = chars.iter().collect();
110 if unique.len() != chars.len() {
111 return Err("字符集包含重复字符".to_string());
112 }
113
114 let charset: Vec<CharElement> = chars
115 .into_iter()
116 .enumerate()
117 .map(|(i, c)| CharElement::new(c, i))
118 .collect();
119
120 let modulus = charset.len();
121 Ok(Self { charset, modulus })
122 }
123
124 pub fn uppercase_alpha() -> Self {
126 Self::new("ABCDEFGHIJKLMNOPQRSTUVWXYZ").unwrap()
127 }
128
129 pub fn lowercase_alpha() -> Self {
131 Self::new("abcdefghijklmnopqrstuvwxyz").unwrap()
132 }
133
134 pub fn mixed_alpha() -> Self {
136 Self::new("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz").unwrap()
137 }
138
139 pub fn alphanumeric() -> Self {
141 Self::new("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789").unwrap()
142 }
143
144 pub fn printable_ascii() -> Self {
146 let chars: String = (32..=126).map(|c| c as u8 as char).collect();
147 Self::new(&chars).unwrap()
148 }
149
150 fn parse_string(&self, s: &str) -> Result<Vec<CharElement>, String> {
154 s.chars()
155 .map(|c| {
156 self.charset
157 .iter()
158 .find(|elem| elem.value() == c)
159 .cloned()
160 .ok_or_else(|| format!("字符 '{}' 不在字符集中", c))
161 })
162 .collect()
163 }
164
165 pub fn encrypt(&self, plaintext: &str, key: &str) -> Result<String, String> {
182 if key.is_empty() {
183 return Err("密钥不能为空".to_string());
184 }
185
186 let key_elements = self.parse_string(key)?;
187
188 let mut result = String::new();
189 let mut key_index = 0;
190
191 for ch in plaintext.chars() {
192 if let Some(elem) = self.charset.iter().find(|e| e.value() == ch) {
193 let key_elem = &key_elements[key_index % key_elements.len()];
194 let new_index = (elem.index() + key_elem.index()) % self.modulus;
195 result.push(self.charset[new_index].value());
196 key_index += 1;
197 } else {
198 result.push(ch); }
200 }
201
202 Ok(result)
203 }
204
205 pub fn decrypt(&self, ciphertext: &str, key: &str) -> Result<String, String> {
222 if key.is_empty() {
223 return Err("密钥不能为空".to_string());
224 }
225
226 let key_elements = self.parse_string(key)?;
227
228 let mut result = String::new();
229 let mut key_index = 0;
230
231 for ch in ciphertext.chars() {
232 if let Some(elem) = self.charset.iter().find(|e| e.value() == ch) {
233 let key_elem = &key_elements[key_index % key_elements.len()];
234 let new_index = (elem.index() + self.modulus - key_elem.index()) % self.modulus;
235 result.push(self.charset[new_index].value());
236 key_index += 1;
237 } else {
238 result.push(ch); }
240 }
241
242 Ok(result)
243 }
244
245 pub fn charset_info(&self) -> String {
247 let chars: String = self.charset.iter().map(|e| e.value()).collect();
248 format!("字符集大小: {}, 字符: \"{}\"", self.modulus, chars)
249 }
250}
251
252#[cfg(test)]
255mod tests {
256 use super::*;
257
258 #[test]
261 fn test_string_basic_encryption() {
262 let cipher = StringCipher::uppercase_alpha();
263 let encrypted = cipher.encrypt("HELLO", "KEY").unwrap();
264 assert_eq!(encrypted, "RIJVS");
265 }
266
267 #[test]
268 fn test_string_basic_decryption() {
269 let cipher = StringCipher::uppercase_alpha();
270 let decrypted = cipher.decrypt("RIJVS", "KEY").unwrap();
271 assert_eq!(decrypted, "HELLO");
272 }
273
274 #[test]
275 fn test_string_round_trip() {
276 let cipher = StringCipher::alphanumeric();
277 let original = "Hello123World";
278 let encrypted = cipher.encrypt(original, "SecretKey").unwrap();
279 let decrypted = cipher.decrypt(&encrypted, "SecretKey").unwrap();
280 assert_eq!(original, decrypted);
281 }
282
283 #[test]
284 fn test_string_custom_charset() {
285 let cipher = StringCipher::new("0123456789").unwrap();
286 let encrypted = cipher.encrypt("123", "456").unwrap();
287 assert_eq!(encrypted, "579");
288 }
289
290 #[test]
291 fn test_string_preserve_unknown_chars() {
292 let cipher = StringCipher::uppercase_alpha();
293 let encrypted = cipher.encrypt("HELLO, WORLD!", "KEY").unwrap();
294 assert_eq!(encrypted, "RIJVS, UYVJN!");
296 }
297
298 #[test]
299 fn test_string_empty_key_error() {
300 let cipher = StringCipher::uppercase_alpha();
301 assert!(cipher.encrypt("HELLO", "").is_err());
302 }
303
304 #[test]
305 fn test_string_invalid_key_char() {
306 let cipher = StringCipher::uppercase_alpha();
307 assert!(cipher.encrypt("HELLO", "key").is_err()); }
309
310 #[test]
311 fn test_string_duplicate_charset_error() {
312 let result = StringCipher::new("ABBA");
313 assert!(result.is_err());
314 }
315
316 #[test]
319 fn test_generic_cipher_with_char_elements() {
320 let charset: Vec<CharElement> = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
322 .chars()
323 .enumerate()
324 .map(|(i, c)| CharElement::new(c, i))
325 .collect();
326
327 let cipher = VigenereCipher::new(NonEmptyVec::try_from_vec(charset.clone()).unwrap());
328
329 let plaintext = vec![
332 charset[7].clone(), charset[4].clone(), charset[11].clone(), charset[11].clone(), charset[14].clone(), ];
338
339 let key = vec![
340 charset[10].clone(), charset[4].clone(), charset[24].clone(), ];
344
345 let encrypted = cipher.encrypt(&plaintext, NonEmptySliceRef::new(key.as_slice()).unwrap());
346
347 assert_eq!(encrypted[0].value(), 'R');
349 assert_eq!(encrypted[1].value(), 'I');
350 assert_eq!(encrypted[2].value(), 'J');
351 assert_eq!(encrypted[3].value(), 'V');
352 assert_eq!(encrypted[4].value(), 'S');
353
354 let decrypted = cipher.decrypt(&encrypted, NonEmptySliceRef::new(key.as_slice()).unwrap());
356 assert_eq!(decrypted[0].value(), 'H');
357 assert_eq!(decrypted[1].value(), 'E');
358 assert_eq!(decrypted[2].value(), 'L');
359 assert_eq!(decrypted[3].value(), 'L');
360 assert_eq!(decrypted[4].value(), 'O');
361 }
362
363 #[test]
364 fn test_generic_cipher_with_digit_elements() {
365 let charset: Vec<DigitElement> = (0..10)
367 .map(|i| DigitElement::new(i).unwrap())
368 .collect();
369
370 let cipher = VigenereCipher::new(NonEmptyVec::try_from_vec(charset.clone()).unwrap());
371
372 let plaintext = vec![
373 charset[1].clone(), charset[2].clone(), charset[3].clone(), ];
377
378 let key = vec![
379 charset[4].clone(), charset[5].clone(), charset[6].clone(), ];
383
384 let encrypted = cipher.encrypt(&plaintext, NonEmptySliceRef::new(key.as_slice()).unwrap());
385
386 assert_eq!(encrypted[0].to_char(), '5');
388 assert_eq!(encrypted[1].to_char(), '7');
389 assert_eq!(encrypted[2].to_char(), '9');
390
391 let decrypted = cipher.decrypt(&encrypted, NonEmptySliceRef::new(key.as_slice()).unwrap());
392 assert_eq!(decrypted[0].to_char(), '1');
393 assert_eq!(decrypted[1].to_char(), '2');
394 assert_eq!(decrypted[2].to_char(), '3');
395 }
396
397 #[test]
398 fn test_cipher_element_index() {
399 let elem = CharElement::new('A', 0);
400 assert_eq!(elem.index(), 0);
401 assert_eq!(elem.value(), 'A');
402
403 let elem2 = CharElement::new('Z', 25);
404 assert_eq!(elem2.index(), 25);
405 assert_eq!(elem2.value(), 'Z');
406 }
407
408 #[test]
409 fn test_digit_element() {
410 let digit = DigitElement::new(5).unwrap();
411 assert_eq!(digit.index(), 5);
412 assert_eq!(digit.to_char(), '5');
413 assert_eq!(digit.value(), 5);
414
415 assert!(DigitElement::new(10).is_none());
417 assert!(DigitElement::new(0).is_some());
418 assert!(DigitElement::new(9).is_some());
419 }
420}
421