Skip to content

Instantly share code, notes, and snippets.

@newton-migosi
Created April 7, 2018 12:28
Show Gist options
  • Save newton-migosi/2b682aaafb8f797de8e30fd10f24fb2c to your computer and use it in GitHub Desktop.
Save newton-migosi/2b682aaafb8f797de8e30fd10f24fb2c to your computer and use it in GitHub Desktop.
Learning rust using caesar cypher
fn encrypt_decrypt(plaintext: &str, key: usize) -> String{
let alphabet = "ABCDFGHIJKLMNOPQRSTUVWXYZ";
let plaintext = &plaintext.to_uppercase();
let mut ciphertext = String::from("");
//println!("{}", plaintext);
//MORINGA
for each_char in plaintext.chars(){
//println!("char {}", each_char);
match alphabet.find(each_char) {
Some(index) => {
let char_index = (index + key) % 26;
let char_place = alphabet.chars().nth(char_index).unwrap();
ciphertext.push(char_place);
},
None => ciphertext.push(each_char)
}
}
//println!("{}", ciphertext);
ciphertext
}
fn main() {
let encrypt_key = 4;
let plain_text = "MORINGA";
let cyphertext = encrypt_decrypt(&plain_text, encrypt_key);
let plain_text_copy = encrypt_decrypt(&cyphertext, 26-encrypt_key);
println!("{} \n{} \n{}", plain_text, cyphertext, plain_text_copy);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment