Skip to content

Instantly share code, notes, and snippets.

@kezzyhko
Last active November 5, 2020 17:54
Show Gist options
  • Save kezzyhko/5e998c3959f34342c674756004e8e3cf to your computer and use it in GitHub Desktop.
Save kezzyhko/5e998c3959f34342c674756004e8e3cf to your computer and use it in GitHub Desktop.
Restore base64 after it was accedentally lowercased (InnoCTF task)

This is a solution to one of the tasks in InnoCTF (2018, I think?)
The task is as follows:

$s1 and $s2 strings were gotten in the following way:

$s1 = strtolower(base64_encode($secret))
$s2 = strtolower(base64_encode(base64_encode($secret)))

Restore $secret.

<?php
//$s1 = 'sw5mb3jtyxrpb24gd2fudhmgdg8gymugsw5ub0nurntmcjmzxzfuzjbybtq3mtbufsbmcmvlica=';
//$s2 = 'u1c1bwizsnrzwfjwyji0z2qyrnvkse1nzec4z1ltvwdtvzv1yjbovvjudg1jak16whpgdvpqqnlivfeztvrcdwztqm1jbvzssunbpq==';
//$s1 == strtolower(base64_encode($secret))
//$s2 == strtolower(base64_encode(base64_encode($secret)))
//return $secret
function restore_base64($s1, $s2) {
$res = '';
for ($i = 0; $i<=strlen($s1)/3; $i++) {
$sx = substr($s1, $i*3, 3);
$s = $sx;
$mode = 0;
while (strtolower(base64_encode($s)) != substr($s2, $i*4, 4)) {
//echo $s;
switch ($mode) {
case 0:
$s = strtoupper($sx[0]) . $sx[1] . $sx[2];
break;
case 1:
$s = $sx[0] . strtoupper($sx[1]) . $sx[2];
break;
case 2:
$s = $sx[0] . $sx[1] . strtoupper($sx[2]);
break;
case 3:
$s = strtoupper($sx[0]) . strtoupper($sx[1]) . $sx[2];
break;
case 4:
$s = $sx[0] . strtoupper($sx[1]) . strtoupper($sx[2]);
break;
case 5:
$s = strtoupper($sx[0]) . $sx[1] . strtoupper($sx[2]);
break;
case 6:
$s = strtoupper($sx[0]) . strtoupper($sx[1]) . strtoupper($sx[2]);
break;
}
$mode++;
}
$res .= $s;
}
return base64_decode($res);
}
<pre><?php
ini_set('max_execution_time', '0');
$sock = fsockopen("innoctf.ru:5005");
while ($in = fread($sock,255)) {
echo "> $in\r\n";
$in = explode("\n", $in);
$s1 = trim($in[0]);
$s2 = strtolower(trim($in[1]));
$res = '';
for ($i = 0; $i<=strlen($s1)/3; $i++) {
$sx = substr($s1, $i*3, 3);
$s = $sx;
$mode = 0;
while (strtolower(base64_encode($s)) != substr($s2, $i*4, 4)) {
echo $s;
switch ($mode) {
case 0:
$s = strtoupper($sx[0]) . $sx[1] . $sx[2];
break;
case 1:
$s = $sx[0] . strtoupper($sx[1]) . $sx[2];
break;
case 2:
$s = $sx[0] . $sx[1] . strtoupper($sx[2]);
break;
case 3:
$s = strtoupper($sx[0]) . strtoupper($sx[1]) . $sx[2];
break;
case 4:
$s = $sx[0] . strtoupper($sx[1]) . strtoupper($sx[2]);
break;
case 5:
$s = strtoupper($sx[0]) . $sx[1] . strtoupper($sx[2]);
break;
case 6:
$s = strtoupper($sx[0]) . strtoupper($sx[1]) . strtoupper($sx[2]);
break;
}
$mode++;
}
$res .= $s;
}
$out = base64_decode($res);
fwrite($sock, "$out\n");
echo "< $out\r\n";
echo '<!--' . str_repeat('x', 999) . '-->';
flush();
}
fclose($sock);
echo '</pre>';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment