Created
April 7, 2018 12:47
-
-
Save rust-play/908585224d3dc888c7b8c1a273a9df9f to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[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