Jump to content

Vigenère cipher: Difference between revisions

m
Line 2,250:
 
=={{header|Rust}}==
{{works with|Rust|0.9}}
<lang Rust>fn uppercase_and_filter(in: &str) -> ~[u8] {
<lang Rust>use std::ascii::AsciiCast;
let mut result = ~[];
use std::str::from_utf8;
 
conststatic A: u8 = 'A' as u8;
for in.each_char |c| {
static a: u8 = 'a' as u8;
if char::is_ascii(c) {
 
if char::is_lowercase(c) {
<lang Rust>fn uppercase_and_filter(ininput: &str) -> ~[u8] {
// We know it's ascii, so just do the math directly
let mut result.push((c + ('A' - 'a')) as= u8)~[];
} else if char::is_uppercase(c) {
for b in input.bytes() {
result.push(c as u8);
if b.is_ascii() }{
let ascii }= b.to_ascii();
if char::is_asciiascii.is_lower(c) {
// We know it's ascii, so just do the math directly
result.push((b + (A - a)))
} else if char::is_uppercaseascii.is_upper(c) {
result.push(c as u8b);
}
}
}
 
return result;
}
 
fn vigenere(key: &str, text: &str, is_encoding: bool) -> ~str {
const A: u8 = 'A' as u8;
let text_byteskey_bytes = uppercase_and_filter(textkey);
 
let key_bytestext_bytes = uppercase_and_filter(keytext);
let text_bytes = uppercase_and_filter(text);
let mut resultresult_bytes = ~[];
 
let mut result_bytes = ~[];
let mut i = 0;
 
for c forin text_bytes.eachi |i, &c|iter() {
let c2 = if is_encoding {
(c + key_bytes[i % key_bytes.len()] - 2 * A) % 26 + A
} else {
(c - key_bytes[i % key_bytes.len()] + 26) % 26 + A
};
result_bytes.push(c2);
}i += 1;
}
 
return str::from_bytesfrom_utf8(result_bytes).to_owned();
}
 
fn main() {
let text = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!";
let key = "VIGENERECIPHER";
io::println(fmt!("Text: %{:s}", text));
io::println(fmt!("Key: %{:s}", key));
let encoded = vigenere(key, text, true);
io::println(fmt!("Code: %{:s}", encoded));
let decoded = vigenere(key, encoded, false);
io::println(fmt!("Back: %{:s}", decoded));
}</lang>
 
io::println(fmt!("Text: %s", text));
io::println(fmt!("Key: %s", key));
 
let encoded = vigenere(key, text, true);
io::println(fmt!("Code: %s", encoded));
let decoded = vigenere(key, encoded, false);
io::println(fmt!("Back: %s", decoded));
}
</lang>
=={{header|Scala}}==
Valid characters for messages: A through Z, zero, 1 to 9, and full-stop (.)
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.