-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem59.php
More file actions
54 lines (49 loc) · 1.15 KB
/
Copy pathProblem59.php
File metadata and controls
54 lines (49 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<?php
/*
* Prompt: Using {assets/p059_cipher.txt}, a file containing the encrypted ASCII codes, and the knowledge that the plain text must contain common English words, decrypt the message and find the sum of the ASCII values in the original text.
*
* Execute: php Problem59.php
*
* Answer: 107359
*/
$cipher = file_get_contents('assets/p059_cipher.txt');
$cipher = trim($cipher);
$cipher = explode(',', $cipher);
function encrypt($text, $key) {
$decrypted = []; // Decrypted Text
$i = 0; // Index on key array
foreach ($text as $c) {
$decrypted[] = $c ^ $key[$i];
$i++;
if (count($key) <= $i) {
$i = 0;
}
}
return $decrypted;
}
function toASCIIArray($input) {
$array = [];
foreach (str_split($input) as $c) {
$array[] = ord($c);
}
return $array;
}
function toString($input) {
$str = "";
foreach ($input as $c) {
$str .= chr($c);
}
return $str;
}
$pass = "aaa";
while (strlen($pass) < 4) {
$key = toASCIIArray($pass);
$dec = encrypt($cipher, $key);
$str = toString($dec);
// "English" dectector
if (!preg_match("/[^A-Za-z0-9 !'(),.;]/", $str)) {
echo array_sum($dec) . PHP_EOL;
exit;
}
$pass++;
}