ferric_crypto_lib 0.2.7

A library for Ferric Crypto
Documentation
/// Encrypts a given plaintext string using a transposition cipher.
///
/// The function pads the plaintext so that it fits into a rectangle, then populates a grid with the padded plaintext.
/// The grid is then read by columns to create the ciphertext.
///
/// # Arguments
///
/// * `plaintext` - A string slice that holds the text to be encrypted.
/// * `key` - The size of the grid's columns, which also determines the level of transposition.
///
/// # Returns
///
/// * A String that represents the encrypted text.
fn encrypt(plaintext: &str, key: usize) -> String {
    let mut ciphertext = String::new();
    // Pad the plaintext so that it fits into a rectangle
    let padded_length = (plaintext.len() + key - 1) / key * key;
    let mut padded_plaintext = plaintext.to_string();
    padded_plaintext.extend(std::iter::repeat('.').take(padded_length - plaintext.len()));

    // Create the grid and populate it with the padded plaintext
    let mut grid = vec![vec!['.'; key]; padded_length / key];
    for (i, ch) in padded_plaintext.chars().enumerate() {
        let row = i / key;
        let col = i % key;
        grid[row][col] = ch;
    }

    // Read the grid by columns to create the ciphertext
    for col in 0..key {
        for row in &grid {
            ciphertext.push(row[col]);
        }
    }

    ciphertext
}

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

    #[test]
    fn simple_encrypt() {
        let result = encrypt("Hello, world!", 4);
        assert_eq!(result, "Hoo!e,r.l l.lwd.");
    }
}