-------------------------------------------
A common security method used for online banking is to ask the user for three random characters from a passcode. For example, if the passcode was 531278, they may asked for the 2nd, 3rd, and 5th characters; the expected reply would be: 317.
The text file, keylog.txt, contains fifty successful login attempts.
Given that the three characters are always asked for in order, analyse the file so as to determine the shortest possible secret passcode of unknown length.
-------------------------------------------
So solution in C# is this, not optimized, but works (in a 16 seconds):
static int[] ReadKeyLog(string file)
{
int[] dig;
string buf;
string[] barr;
StreamReader sr = new StreamReader(file);
buf = sr.ReadToEnd().TrimEnd("\n".ToCharArray());
barr = buf.Split("\n".ToCharArray());
dig = Array.ConvertAll(barr, s => { return Int32.Parse(s); });
sr.Close();
return dig;
}
static bool KeyPartExists(long testnumber, int keypart)
{
int n1 = keypart / 100;
int n2 = (keypart / 10) % 10;
int n3 = keypart % 10;
bool n1e = false;
bool n2e = false;
bool n3e = false;
for (long i = testnumber; i > 0; i /= 10)
{
if (!n3e)
n3e = (i % 10) == n3;
else
if (!n2e)
n2e = (i % 10) == n2;
else
if (!n1e)
n1e = (i % 10) == n1;
else
break;
}
if (n1e && n2e && n3e)
return true;
else
return false;
}
static bool HasAllKeyParts(long testnum, int[] keylog)
{
bool res = true;
for (int i = 0; i < keylog.Length; i++)
{
if (!KeyPartExists(testnum, keylog[i]))
{
res = false;
break;
}
}
return res;
}
static long FindPassCode(string file)
{
int[] keylog = ReadKeyLog(file);
long num = 10000;
while (true)
{
if (HasAllKeyParts(num, keylog))
return num;
num++;
}
}
static void Main(string[] args)
{
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
Console.WriteLine("Bruteforced passcode is {0}",
FindPassCode("C:\\ProjectEuler\\keylog.txt")
);
sw.Stop();
Console.WriteLine("Cracking time {0} seconds", sw.Elapsed.Seconds);
Console.ReadLine();
}
please re-paste your code and wrap it in a pre tag. (you'll need opening at the beginning of your code snippet and closing at the end
ReplyDeleteIt makes reading it easier
ReplyDeleteDone. Thanks for note.
ReplyDeletemuch much better
ReplyDelete