Skip to content

Instantly share code, notes, and snippets.

@maretekent
Forked from rust-play/playground.rs
Created April 7, 2018 12:47
Show Gist options
  • Save maretekent/e5c70c922644e8766161332ed5bafa68 to your computer and use it in GitHub Desktop.
Save maretekent/e5c70c922644e8766161332ed5bafa68 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
#[allow(dead_code)]
fn encrypt(plaintext: &str, key: usize){
let plaintext = &plaintext.to_uppercase();
let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let mut cipher = String::from("");
for each_char in plaintext.chars(){
match alphabet.find(each_char) {
Some(index) => {
let char_index = (index + key) % 26;
let char_place = alphabet.chars().nth(char_index).unwrap();
cipher.push(char_place);
},
None => cipher.push(each_char)
}
}
println!("Result {}", cipher);
}
fn decrypt(cipher: &str, key: usize){
let cipher = &cipher.to_uppercase();
let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let mut plaintext = String::from("");
for each_char in cipher.chars(){
match alphabet.find(each_char) {
Some(index) => {
let char_index = (key - 26) % index;
let char_place = alphabet.chars().nth(char_index).unwrap();
plaintext.push(char_place);
},
None => plaintext.push(each_char)
}
}
println!("Result {}", plaintext);
}
fn main(){
//encrypt("MORINGA", 4);
decrypt("QSVMRKE", 4);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment