home

Scientific Computing (Psychology 9040a)

Fall, 2021

Project Euler Problem 59


Solve Project Euler Problem 59.

Hints

bitwise XOR in MATLAB

The MATLAB function bitxor() will perform the XOR operation on bytes of data. To encrypt a string of characters like hello! you can first convert the character string into 8-bit integer bytes using the int8() function. Here is a small example of encrypting the character string hello! using the encryption key me, repeated 3 times to match the number of characters of the string to be encrypted:

% encryption
plaintext = 'hello!';
key = 'me';
plaintext_bytes = int8(plaintext);
key_bytes = int8(key);
ciphertext_bytes = bitxor(plaintext_bytes, repmat(key_bytes, 1, 3));
disp(ciphertext_bytes)

Here is an example of decrypting the ciphertext using the (known) key:

% decryption
ciphertext_bytes = int8([5,0,1,9,2,68]);
key = 'me';
key_bytes = int8(key);
plaintext_bytes = bitxor(ciphertext_bytes, repmat(key_bytes, 1, 3));
plaintext = char(plaintext_bytes);
disp(plaintext)

Loading the cipher text

You can use the MATLAB function load() to load the cipher text. Assume the cipher text is saved in a file called p059_cipher.txt. The file is available for download on the Project Euler Problem 59 page (last paragraph). Once you have downloaded it, here is how you can load the file in MATLAB:

cipher = load('p059_cipher.txt');

finding a string within another string

In older versions of MATLAB you can use the function findstr() to test whether one string is a substring of another string (for example if the word ‘the’ is present within a decrypted message). Current versions of MATLAB have the function contains() which according to MATLAB is the current preferred function over findstr().

The answer

You’ll know when you find the correct key because the decrypted message will be an English language sentence. You’ll also know because the sum of the integer values of the plaintext message is 129448.