Rust Implementation of Problem 59

View source code here on GitHub!

Includes

Problem Solution

pub fn problems::p0059::p0059() -> utils::Answer
 1/*
 2Project Euler Problem 59
 3
 4Problem:
 5
 6Each character on a computer is assigned a unique code and the preferred
 7standard is ASCII (American Standard Code for Information Interchange). For
 8example, uppercase A = 65, asterisk (*) = 42, and lowercase k = 107.
 9
10A modern encryption method is to take a text file, convert the bytes to ASCII,
11then XOR each byte with a given value, taken from a secret key. The advantage
12with the XOR function is that using the same encryption key on the cipher text,
13restores the plain text; for example, 65 XOR 42 = 107, then 107 XOR 42 = 65.
14
15For unbreakable encryption, the key is the same length as the plain text
16message, and the key is made up of random bytes. The user would keep the
17encrypted message and the encryption key in different locations, and without
18both "halves", it is impossible to decrypt the message.
19
20Unfortunately, this method is impractical for most users, so the modified
21method is to use a password as a key. If the password is shorter than the
22message, which is likely, the key is repeated cyclically throughout the
23message. The balance for this method is using a sufficiently long password key
24for security, but short enough to be memorable.
25
26Your task has been made easy, as the encryption key consists of three lower
27case characters. Using cipher.txt (right click and 'Save Link/Target As...'),
28a file containing the encrypted ASCII codes, and the knowledge that the plain
29text must contain common English words, decrypt the message and find the sum of
30the ASCII values in the original text.
31*/
32use itertools::Itertools;
33
34use crate::include::utils::{get_data_file,Answer};
35
36pub fn p0059() -> Answer {
37    let keyword = b"beginning";
38    let tokens = get_data_file("p0059_cipher.txt").trim()
39                                                  .split(',')
40                                                  .map(|x| x.parse::<u8>().unwrap())
41                                                  .collect::<Vec<u8>>();
42    for key in b"abcdefghijklmnopqrtsuvwxyz".iter().permutations(3) {
43        let plaintext = tokens.iter()
44                              .zip(key.into_iter().cycle())
45                              .map(|(&x, k)| x ^ k)
46                              .collect::<Vec<u8>>();
47        if plaintext.windows(keyword.len()).any(|w| w == keyword) {
48            return Answer::Int(
49                plaintext.into_iter()
50                         .map(Into::<u64>::into)
51                         .sum::<u64>()
52                         .into()
53            );
54        }
55    }
56    return Answer::Int(-1);
57}

Tags: cryptography, binary-operator, xor, file-io