caesar Algorithm
The Caesar Cipher Algorithm is one of the most basic and earliest known encryption techniques in the history of cryptography. Named after Julius Caesar, who is believed to have used it to communicate with his military generals, this algorithm is a substitution cipher that involves replacing each letter in the plaintext by a letter some fixed number of positions down the alphabet. For instance, with a shift of 3, the letter 'A' would be replaced by 'D', 'B' would become 'E', and so on. The shift value acts as a key for the encryption and decryption process.
Despite its simplicity, the Caesar Cipher was once considered effective in maintaining the secrecy of messages, primarily due to the low literacy rate and lack of knowledge about cryptography at that time. However, in modern times, this algorithm is considered extremely weak and can be easily broken using frequency analysis or even by brute force, trying all possible shift values. Today, the Caesar Cipher serves as a fundamental building block and an educational tool for understanding the basic principles of encryption and cryptography.
//! Caesar Cipher
//! Based on cipher_crypt::caesar
//!
//! # Algorithm
//!
//! Rotate each ascii character by shift. The most basic example is ROT 13, which rotates 'a' to
//! 'n'. This implementation does not rotate unicode characters.
/// Caesar cipher to rotate cipher text by shift and return an owned String.
pub fn caesar(cipher: &str, shift: u8) -> String {
cipher
.chars()
.map(|c| {
if c.is_ascii_alphabetic() {
let first = if c.is_ascii_lowercase() { b'a' } else { b'A' };
// modulo the distance to keep character range
(first + (c as u8 + shift - first) % 26) as char
} else {
c
}
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty() {
assert_eq!(caesar("", 13), "");
}
#[test]
fn caesar_rot_13() {
assert_eq!(caesar("rust", 13), "ehfg");
}
#[test]
fn caesar_unicode() {
assert_eq!(caesar("attack at dawn 攻", 5), "fyyfhp fy ifbs 攻");
}
}