Vigenère cipher: Difference between revisions

Content added Content deleted
Line 2,250: Line 2,250:


=={{header|Rust}}==
=={{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;


static 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) {
fn uppercase_and_filter(input: &str) -> ~[u8] {
// We know it's ascii, so just do the math directly
result.push((c + ('A' - 'a')) as u8)
let mut result = ~[];
} 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 ascii.is_lower() {
// We know it's ascii, so just do the math directly
result.push((b + (A - a)))
} else if ascii.is_upper() {
result.push(b);
}
}
}
}

return result;
return result;
}
}

fn vigenere(key: &str, text: &str, is_encoding: bool) -> ~str {
fn vigenere(key: &str, text: &str, is_encoding: bool) -> ~str {
const A: u8 = 'A' as u8;
let key_bytes = uppercase_and_filter(key);

let key_bytes = uppercase_and_filter(key);
let text_bytes = uppercase_and_filter(text);
let text_bytes = uppercase_and_filter(text);
let mut result_bytes = ~[];

let mut result_bytes = ~[];
let mut i = 0;

for text_bytes.eachi |i, &c| {
for c in text_bytes.iter() {
let c2 = if is_encoding {
let c2 = if is_encoding {
(c + key_bytes[i % key_bytes.len()] - 2 * A) % 26 + A
(c + key_bytes[i % key_bytes.len()] - 2 * A) % 26 + A
} else {
} else {
(c - key_bytes[i % key_bytes.len()] + 26) % 26 + A
(c - key_bytes[i % key_bytes.len()] + 26) % 26 + A
};
};
result_bytes.push(c2);
result_bytes.push(c2);
}
i += 1;
}

return str::from_bytes(result_bytes);
return from_utf8(result_bytes).to_owned();
}
}

fn main() {
fn main() {
let text = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!";
let text = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!";
let key = "VIGENERECIPHER";
let key = "VIGENERECIPHER";
println!("Text: {:s}", text);
println!("Key: {:s}", key);
let encoded = vigenere(key, text, true);
println!("Code: {:s}", encoded);
let decoded = vigenere(key, encoded, false);
println!("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}}==
=={{header|Scala}}==
Valid characters for messages: A through Z, zero, 1 to 9, and full-stop (.)
Valid characters for messages: A through Z, zero, 1 to 9, and full-stop (.)