ruscrypt 0.3.2

⚡ Lightning-fast cryptography toolkit built with Rust - A comprehensive CLI tool for classical and modern cryptographic operations
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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
//! # Command Dispatcher Module
//!
//! This module handles the routing and execution of CLI commands. It takes parsed
//! command-line arguments and dispatches them to the appropriate cryptographic
//! functions while providing user interaction and formatted output.
//!
//! ## Architecture
//!
//! The dispatcher follows a pattern where:
//! 1. Commands are parsed and displayed to the user
//! 2. Interactive prompts gather necessary parameters
//! 3. Appropriate cryptographic functions are called
//! 4. Results are formatted and displayed
//!
//! ## Error Handling
//!
//! All functions return `Result<()>` to enable proper error propagation
//! and user-friendly error messages.

use anyhow::Result;
use colored::*;

use crate::asym::{dh, rsa};
use crate::block::{aes, des};
use crate::classical::{caesar, playfair, rail_fence, vigenere};
use crate::cli::{
    Commands, EncryptionAlgorithm, ExchangeProtocol, HashAlgorithm, KeygenAlgorithm,
    SigningAlgorithm,
};
use crate::hash::{md5, sha1, sha256};
use crate::stream::rc4;
use crate::{cli, interactive};

/// Dispatch and execute the appropriate command based on parsed CLI arguments
pub fn dispatch_command(args: cli::Args) -> Result<()> {
    match args.command {
        Commands::Encrypt { algorithm } => {
            let algo_name = cli::get_algorithm_name(&algorithm);
            println!(
                "{} {}",
                "🔒 Encrypting with".green(),
                algo_name.yellow().bold()
            );
            handle_encryption(algorithm)?;
        }
        Commands::Decrypt { algorithm } => {
            let algo_name = cli::get_algorithm_name(&algorithm);
            println!(
                "{} {}",
                "🔓 Decrypting with".blue(),
                algo_name.yellow().bold()
            );
            handle_decryption(algorithm)?;
        }
        Commands::Hash { algorithm } => {
            let algo_name = cli::get_hash_algorithm_name(&algorithm);
            println!(
                "{} {}",
                "🔢 Hashing with".magenta(),
                algo_name.yellow().bold()
            );
            handle_hashing(algorithm)?;
        }
        Commands::Exchange { protocol } => {
            let protocol_name = cli::get_keyexchange_protocol_name(&protocol);
            println!(
                "{} {}",
                "🔑 Key Exchange with".purple(),
                protocol_name.yellow().bold()
            );
            handle_key_exchange(protocol)?;
        }
        Commands::Keygen { algorithm } => {
            let algo_name = cli::get_keygen_algorithm_name(&algorithm);
            println!(
                "{} {}",
                "🔑 Generating key for".cyan(),
                algo_name.yellow().bold()
            );
            handle_keygen(algorithm)?;
        }
        Commands::Sign { algorithm } => {
            let algo_name = cli::get_signing_algorithm_name(&algorithm);
            println!("✍️ Signing with {algo_name} algorithm...");

            if algorithm.rsa {
                handle_sign(algorithm)?;
            }
        }
        Commands::Verify { algorithm } => {
            let algo_name = cli::get_signing_algorithm_name(&algorithm);
            println!("🔍 Verifying {algo_name} signature...");

            if algorithm.rsa {
                handle_verify(algorithm)?;
            }
        }
    }

    Ok(())
}

/// Handle encryption operations for all supported algorithms
///
/// This function manages the encryption workflow by:
/// 1. Prompting for input text
/// 2. Gathering algorithm-specific parameters (keys, shifts, etc.)
/// 3. Calling the appropriate encryption function
/// 4. Displaying the encrypted result
///
/// # Arguments
///
/// * `algorithm` - The encryption algorithm configuration specifying which algorithm to use
///
/// # Returns
///
/// Returns `Ok(())` on successful encryption, or an error if the operation fails.
///
/// # Interactive Prompts
///
/// Depending on the algorithm, this function may prompt for:
/// - Shift values (Caesar cipher)
/// - Keywords (Vigenère, Playfair)
/// - Keys and passwords (RC4, AES, DES, RSA)
/// - Encoding preferences (base64, hex)
/// - Algorithm parameters (key sizes, modes)
///
/// # Errors
///
/// Can return errors from:
/// - Invalid user input
/// - Cryptographic operation failures
/// - I/O errors during prompts
/// - Algorithm-specific validation failures
fn handle_encryption(algorithm: EncryptionAlgorithm) -> Result<()> {
    let input = interactive::prompt_for_input("Enter text to encrypt")?;

    let result = match true {
        _ if algorithm.caesar => {
            let shift = interactive::prompt_for_number("Enter shift value (1-25)", 1, 25)?;
            let encrypted = caesar::encrypt(&input, shift as u8)?;
            format!("Encrypted text: {encrypted}")
        }
        _ if algorithm.vigenere => {
            let keyword = interactive::prompt_for_input("Enter keyword")?;
            let encrypted = vigenere::encrypt(&input, &keyword)?;
            format!("Encrypted text: {encrypted}")
        }
        _ if algorithm.playfair => {
            let keyword = interactive::prompt_for_input("Enter keyword for matrix")?;
            let encrypted = playfair::encrypt(&input, &keyword)?;
            format!("Encrypted text: {encrypted}")
        }
        _ if algorithm.railfence => {
            let rails = interactive::prompt_for_number("Enter number of rails (2-10)", 2, 10)?;
            let encrypted = rail_fence::encrypt(&input, rails as usize)?;
            format!("Encrypted text: {encrypted}")
        }
        _ if algorithm.rc4 => {
            let key = interactive::prompt_for_password("Enter encryption key")?;
            let encoding =
                interactive::prompt_for_choices("Select output encoding", &["base64", "hex"])?;
            let encrypted = rc4::encrypt(&input, &key, &encoding)?;
            format!("Encrypted text ({encoding}): {encrypted}")
        }
        _ if algorithm.aes => {
            let password = interactive::prompt_for_password("Enter password")?;
            let key_size =
                interactive::prompt_for_choices("Select AES key size", &["128", "192", "256"])?;
            let mode = interactive::prompt_for_choices("Select encryption mode", &["ECB", "CBC"])?;
            let encoding =
                interactive::prompt_for_choices("Select output encoding", &["base64", "hex"])?;
            let encrypted = aes::encrypt(&input, &password, &key_size, &mode, &encoding)?;
            format!("Encrypted text (AES-{key_size}, {mode}, {encoding}): {encrypted}")
        }
        _ if algorithm.des => {
            let key = interactive::prompt_for_input("Enter key (exactly 8 characters)")?;
            if key.len() != 8 {
                return Err(anyhow::anyhow!("DES key must be exactly 8 characters long"));
            }
            let mode = interactive::prompt_for_choices("Select encryption mode", &["ECB", "CBC"])?;
            let encoding =
                interactive::prompt_for_choices("Select output encoding", &["base64", "hex"])?;
            let encrypted = des::encrypt(&input, &key, &mode, &encoding)?;
            format!("Encrypted text (DES, {mode}, {encoding}): {encrypted}")
        }
        _ if algorithm.rsa => {
            let key_size =
                interactive::prompt_for_choices("Select RSA key size", &["512", "1024", "2048"])?;
            let encoding =
                interactive::prompt_for_choices("Select output encoding", &["base64", "hex"])?;
            let privkey_format = interactive::prompt_for_choices(
                "Select private key output format",
                &["n:d", "PEM"],
            )?;
            let (encrypted, private_key) =
                rsa::encrypt(&input, &key_size, &encoding, &privkey_format)?;

            println!("\n🔐 RSA Encryption Complete!");
            println!("📤 Encrypted data: {encrypted}");
            println!("🔑 Private key (SAVE THIS!): {private_key}");
            println!("⚠️  Keep your private key secure - you'll need it for decryption!");

            format!("RSA-{key_size} encryption successful. Encrypted data and private key provided above.")
        }
        _ => return Err(anyhow::anyhow!("Unknown algorithm")),
    };

    println!("\n{} {}", "Result:".cyan().bold(), result.white());
    Ok(())
}

/// Handle decryption operations for all supported algorithms
///
/// This function manages the decryption workflow by:
/// 1. Prompting for encrypted text
/// 2. Gathering algorithm-specific parameters (keys, shifts, etc.)
/// 3. Calling the appropriate decryption function
/// 4. Displaying the decrypted result
///
/// # Arguments
///
/// * `algorithm` - The encryption algorithm configuration specifying which algorithm to use
///
/// # Returns
///
/// Returns `Ok(())` on successful decryption, or an error if the operation fails.
///
/// # Interactive Prompts
///
/// Similar to encryption, but may include additional prompts for:
/// - Private keys (RSA)
/// - Initialization vectors (block ciphers)
/// - Input encoding formats (base64, hex)
///
/// # Errors
///
/// Can return errors from:
/// - Invalid encrypted text format
/// - Incorrect keys or parameters
/// - Cryptographic operation failures
/// - Encoding/decoding errors
fn handle_decryption(algorithm: EncryptionAlgorithm) -> Result<()> {
    let input = interactive::prompt_for_input("Enter text to decrypt")?;

    let result = match true {
        _ if algorithm.caesar => {
            let shift = interactive::prompt_for_number("Enter shift value (1-25)", 1, 25)?;
            let decrypted = caesar::decrypt(&input, shift as u8)?;
            format!("Decrypted text: {decrypted}")
        }
        _ if algorithm.vigenere => {
            let keyword = interactive::prompt_for_input("Enter keyword")?;
            let decrypted = vigenere::decrypt(&input, &keyword)?;
            format!("Decrypted text: {decrypted}")
        }
        _ if algorithm.playfair => {
            let keyword = interactive::prompt_for_input("Enter keyword for matrix")?;
            let decrypted = playfair::decrypt(&input, &keyword)?;
            format!("Decrypted text: {decrypted}")
        }
        _ if algorithm.railfence => {
            let rails = interactive::prompt_for_number("Enter number of rails (2-10)", 2, 10)?;
            let decrypted = rail_fence::decrypt(&input, rails as usize)?;
            format!("Decrypted text: {decrypted}")
        }
        _ if algorithm.rc4 => {
            let key = interactive::prompt_for_password("Enter decryption key")?;
            let encoding =
                interactive::prompt_for_choices("Select input encoding", &["base64", "hex"])?;
            let decrypted = rc4::decrypt(&input, &key, &encoding)?;
            format!("Decrypted text: {decrypted}")
        }
        _ if algorithm.aes => {
            let password = interactive::prompt_for_password("Enter password")?;
            let key_size =
                interactive::prompt_for_choices("Select AES key size", &["128", "192", "256"])?;
            let mode = interactive::prompt_for_choices("Select encryption mode", &["ECB", "CBC"])?;
            let encoding =
                interactive::prompt_for_choices("Select input encoding", &["base64", "hex"])?;
            let decrypted = aes::decrypt(&input, &password, &key_size, &mode, &encoding)?;
            format!("Decrypted text: {decrypted}")
        }
        _ if algorithm.des => {
            let key = interactive::prompt_for_input("Enter key (exactly 8 characters)")?;
            if key.len() != 8 {
                return Err(anyhow::anyhow!("DES key must be exactly 8 characters long"));
            }
            let mode = interactive::prompt_for_choices("Select encryption mode", &["ECB", "CBC"])?;
            let encoding =
                interactive::prompt_for_choices("Select input encoding", &["base64", "hex"])?;
            let decrypted = des::decrypt(&input, &key, &mode, &encoding)?;
            format!("Decrypted text: {decrypted}")
        }
        _ if algorithm.rsa => {
            let private_key = interactive::prompt_for_multiline_input(
                "Enter private key (format: n:d or PEM block, end with empty line)",
            )?;
            let encoding =
                interactive::prompt_for_choices("Select input encoding", &["base64", "hex"])?;
            let decrypted = rsa::decrypt(&input, &private_key, &encoding)?;
            format!("Decrypted text: {decrypted}")
        }
        _ => return Err(anyhow::anyhow!("Unknown algorithm")),
    };

    println!("\n{} {}", "Result:".cyan().bold(), result.white());
    Ok(())
}

/// Handle hashing operations for all supported hash functions
///
/// This function manages the hashing workflow by:
/// 1. Prompting for input text
/// 2. Computing the hash using the selected algorithm
/// 3. Displaying the hash value in hexadecimal format
///
/// # Arguments
///
/// * `algorithm` - The hash algorithm configuration specifying which function to use
///
/// # Returns
///
/// Returns `Ok(())` on successful hashing, or an error if the operation fails.
///
/// # Output Format
///
/// Hash values are displayed as hexadecimal strings:
/// - MD5: 32 characters
/// - SHA-1: 40 characters  
/// - SHA-256: 64 characters
///
/// # Errors
///
/// Can return errors from:
/// - Hash computation failures
/// - I/O errors during prompts
/// - Memory allocation issues for large inputs
fn handle_hashing(algorithm: HashAlgorithm) -> Result<()> {
    let input = interactive::prompt_for_input("Enter text to hash")?;

    let result = match true {
        _ if algorithm.md5 => {
            let hash_value = md5::hash(&input)?;
            format!("MD5 hash: {hash_value}")
        }
        _ if algorithm.sha1 => {
            let hash_value = sha1::hash(&input)?;
            format!("SHA-1 hash: {hash_value}")
        }
        _ if algorithm.sha256 => {
            let hash_value = sha256::hash(&input)?;
            format!("SHA-256 hash: {hash_value}")
        }
        _ => return Err(anyhow::anyhow!("Unknown algorithm")),
    };

    println!("\n{} {}", "Result:".blue().bold(), result.white());
    Ok(())
}

/// Handle key exchange protocol operations
///
/// This function manages key exchange workflows by:
/// 1. Presenting protocol-specific options
/// 2. Managing interactive or manual exchange modes
/// 3. Facilitating secure key establishment
/// 4. Displaying shared secrets and educational information
///
/// # Arguments
///
/// * `protocol` - The key exchange protocol configuration
///
/// # Returns
///
/// Returns `Ok(())` on successful key exchange, or an error if the operation fails.
///
/// # Supported Modes
///
/// For Diffie-Hellman:
/// - **Interactive Simulation**: Demonstrates Alice & Bob exchange
/// - **Manual Exchange - Start Session**: Real-world usage with other parties
/// - **Manual Exchange - Complete with Other's Key**: Complete the exchange with a given key
/// - **Mathematical Demo**: Shows the underlying mathematics
///
/// # Security Considerations
///
/// The function provides educational warnings about:
/// - Parameter selection importance
/// - Man-in-the-middle attack risks
/// - Proper implementation requirements
///
/// # Errors
///
/// Can return errors from:
/// - Invalid protocol selection
/// - Mathematical computation failures
/// - User input validation errors
/// - Network communication issues (future implementations)
fn handle_key_exchange(protocol: ExchangeProtocol) -> Result<()> {
    let result = match true {
        _ if protocol.dh => {
            let choice = interactive::prompt_for_choices(
                "Select Diffie-Hellman operation",
                &[
                    "Interactive Simulation (Alice & Bob)",
                    "Manual Exchange - Start Session",
                    "Manual Exchange - Complete with Other's Key",
                    "Mathematical Concept Demo",
                ],
            )?;

            match choice.as_str() {
                "Interactive Simulation (Alice & Bob)" => dh::key_exchange("interactive")?,
                "Manual Exchange - Start Session" => {
                    println!("\n🚀 Starting manual key exchange session...");
                    dh::key_exchange("manual")?
                }
                "Manual Exchange - Complete with Other's Key" => {
                    let other_public_key =
                        interactive::prompt_for_input("Enter other party's public key")?
                            .parse::<u64>()
                            .map_err(|_| {
                                anyhow::anyhow!("Invalid public key format. Must be a number.")
                            })?;

                    let my_private_key = interactive::prompt_for_input("Enter your private key")?
                        .parse::<u64>()
                        .map_err(|_| {
                            anyhow::anyhow!("Invalid private key format. Must be a number.")
                        })?;

                    dh::complete_manual_key_exchange(other_public_key, my_private_key)?
                }
                "Mathematical Concept Demo" => dh::key_exchange("demo")?,
                _ => return Err(anyhow::anyhow!("Invalid choice")),
            }
        }
        _ if protocol.ecdh => "ECDH key exchange is not yet implemented. Coming soon!".to_string(),
        _ => return Err(anyhow::anyhow!("Unknown key exchange protocol")),
    };

    println!("\n{} {}", "Result:".cyan().bold(), result.white());
    Ok(())
}

/// Handle key generation operations for supported algorithms
///
/// This function manages the key generation workflow by:
/// 1. Prompting for key size and output format
/// 2. Calling the appropriate key generation function
/// 3. Displaying the generated keys in the selected format
///
/// # Arguments
///
/// * `algorithm` - The key generation algorithm configuration
///
/// # Returns
///
/// Returns `Ok(())` on successful key generation, or an error if the operation fails.
///
/// # Interactive Prompts
///
/// - Key size (e.g., 512, 1024, 2048 for RSA)
/// - Output format (e.g., "n:e" or "PEM")
///
/// # Errors
///
/// Can return errors from:
/// - Invalid user input
/// - Key generation failures
/// - I/O errors during prompts
fn handle_keygen(algorithm: KeygenAlgorithm) -> Result<()> {
    if algorithm.rsa {
        let key_size: String =
            interactive::prompt_for_choices("Select RSA key size", &["512", "1024", "2048"])?;
        let format = interactive::prompt_for_key_output_format()?;
        let key_size_num = key_size
            .parse::<u32>()
            .map_err(|_| anyhow::anyhow!("Invalid key size"))?;
        let (public_key, private_key) = rsa::keygen_and_export(key_size_num, &format)?;
        println!("\n{} {}", "Public Key:".green().bold(), public_key.white());
        println!("{} {}", "Private Key:".yellow().bold(), private_key.white());
        println!("⚠️  Keep your private key secure!");
        Ok(())
    } else {
        Err(anyhow::anyhow!("Unknown key generation algorithm"))
    }
}

/// Handle RSA signing operations
pub fn handle_sign(algorithm: SigningAlgorithm) -> Result<()> {
    if algorithm.rsa {
        println!("📝 RSA Digital Signature");
        println!("========================");

        let data = interactive::prompt_for_input("Enter message to sign")?;
        let private_key =
            interactive::prompt_for_multiline_input("Enter private key (n:d format or PEM)")?;
        let encoding = interactive::prompt_for_encoding("Select output encoding")?;

        match rsa::sign(&data, &private_key, &encoding) {
            Ok(signature) => {
                println!("\n✅ Digital signature created successfully!");
                println!("📝 Original message: {data}");
                println!(
                    "🔏 Digital signature ({}): {}",
                    encoding.to_uppercase(),
                    signature
                );
                println!("\n💡 Save this signature to verify the message authenticity later.");
            }
            Err(e) => {
                eprintln!("❌ Signing failed: {e}");
                return Err(e);
            }
        }

        Ok(())
    } else {
        Err(anyhow::anyhow!("Unknown signing algorithm"))
    }
}

/// Handle RSA signature verification operations
pub fn handle_verify(algorithm: SigningAlgorithm) -> Result<()> {
    if algorithm.rsa {
        println!("🔍 RSA Signature Verification");
        println!("=============================");

        let data = interactive::prompt_for_input("Enter original message")?;
        let signature = interactive::prompt_for_input("Enter signature to verify")?;
        let public_key =
            interactive::prompt_for_multiline_input("Enter public key (n:e format or PEM)")?;
        let encoding = interactive::prompt_for_encoding("Select signature encoding")?;

        match rsa::verify(&data, &signature, &public_key, &encoding) {
            Ok(is_valid) => {
                println!("\n🔍 Signature verification result:");
                println!("📝 Original message: {data}");
                println!("🔏 Signature: {}...", &signature[..signature.len().min(20)]);

                if is_valid {
                    println!("✅ VALID: The signature is authentic!");
                    println!("🔒 The message integrity is verified and the signature is genuine.");
                } else {
                    println!("❌ INVALID: The signature verification failed!");
                    println!(
                        "⚠️  The message may have been tampered with or the signature is forged."
                    );
                }
            }
            Err(e) => {
                eprintln!("❌ Verification failed: {e}");
                return Err(e);
            }
        }

        Ok(())
    } else {
        Err(anyhow::anyhow!("Unknown verification algorithm"))
    }
}