Rotational Cipher

1. Readme

旋转密码

创建旋转密码的实现,有时也称为 Caesar 密码.

Caesar 密码是一个简单的移位密码,它依赖于使用026整数(key),在字母表中转置所有字母。由于模运算,使用0要么26,总是会产生相同的输出。将字母移动为与 key 值一样多的值。

旋转密码的一般表示法是ROT + <key>。最常用的旋转密码是ROT13.

一个拉丁字母表的ROT13加密如下:

原文:  abcdefghijklmnopqrstuvwxyz
密文:  nopqrstuvwxyzabcdefghijklm

它比 Atbash 密码更强大,因为它有 27 个可能性 key,和 25 个可用的密文.

密文会与输入相同的格式写出,包括空格和标点符号.

例子

  • ROT5 omgtrl
  • ROT0 cc
  • ROT26 CoolCool
  • ROT13 The quick brown fox jumps over the lazy dog.Gur dhvpx oebja sbk whzcf bire gur ynml qbt.
  • ROT13 Gur dhvpx oebja sbk whzcf bire gur ynml qbt.The quick brown fox jumps over the lazy dog.

资源

维基百科https://en.wikipedia.org/wiki/Caesar_cipher

2. 开始你的表演

pub fn rotate(input: &str, key: i8) -> String {
   unimplemented!(
       "How would input text '{}' transform when every letter is shifted using key '{}'?",
       input,
       key
   );
}

3. 测试代码查看


# #![allow(unused_variables)]
#fn main() {
#[test]
fn rotate_a_1() {
   assert_eq!("b", rotate("a", 1));
}

#[test]
//#[ignore]
fn rotate_a_26() {
   assert_eq!("a", rotate("a", 26));
}

#[test]
//#[ignore]
fn rotate_a_0() {
   assert_eq!("a", rotate("a", 0));
}

#[test]
//#[ignore]
fn rotate_m_13() {
   assert_eq!("z", rotate("m", 13));
}

#[test]
//#[ignore]
fn rotate_n_13_with_wrap() {
   assert_eq!("a", rotate("n", 13));
}

#[test]
//#[ignore]
fn rotate_caps() {
   assert_eq!("TRL", rotate("OMG", 5));
}

#[test]
//#[ignore]
fn rotate_spaces() {
   assert_eq!("T R L", rotate("O M G", 5));
}

#[test]
//#[ignore]
fn rotate_numbers() {
   assert_eq!("Xiwxmrk 1 2 3 xiwxmrk", rotate("Testing 1 2 3 testing", 4));
}

#[test]
//#[ignore]
fn rotate_punctuation() {
   assert_eq!("Gzo\'n zvo, Bmviyhv!", rotate("Let\'s eat, Grandma!", 21));
}

#[test]
//#[ignore]
fn rotate_all_the_letters() {
   assert_eq!(
       "Gur dhvpx oebja sbk whzcf bire gur ynml qbt.",
       rotate("The quick brown fox jumps over the lazy dog.", 13)
   );
}

#}

4. 答案


# #![allow(unused_variables)]
#fn main() {
pub fn rotate(text: &str, shift_key: u8) -> String {
   text.chars()
       .map(|c| {
           let case = if c.is_uppercase() { 'A' } else { 'a' } as u8;
           if c.is_alphabetic() {
               (((c as u8 - case + shift_key) % 26) + case) as char
           } else {
               c
           }
       })
       .collect::<String>()
}

#}



填充/相关